views:

31

answers:

2

Hi all, this example below works when hover event is trigered and when its not, its working for elements already in DOM, but when element created dynamically it doesn't work, I realize I need to use jQuery live() or delegate() for this, the thing is I tried to modify it and its not producing the results as expected, here is the working code :

$(".sidebar li").hover(
         function(){
        $(this).css("background-color", "#F9F4D0");
        $(this).append($('<button class="promoter" type="button" title="Active promotion"></button>'));
                  },
        function(){
        $(this).css("background-color", "#F9FAFA");
        $(this).children("button").remove();
                 }    
                     );

Here is the bit when I wanted to add live but it's not producing correct results :

$(".sidebar li").live('hover', function(){
        $(this).css("background-color", "#F9F4D0");
        $(this).append($('<button class="promoter" type="button" title="Active promotion"></button>'));
                  },
        function(){
        $(this).css("background-color", "#F9FAFA");
        $(this).children("button").remove();
                 }    
                     );

Where did I made mistake, thank you

+2  A: 

You can do this:

$(".sidebar li").live('mouseenter', function(){
    $(this).css("background-color", "#F9F4D0");
    $(this).append($('<button class="promoter" type="button" title="Active promotion"></button>'));
}).live('mouseleave', function(){
    $(this).css("background-color", "#F9FAFA");
    $(this).children("button").remove();
});

The .live('hover', function() {}) shorthand works for things like $(this).children().slideToggle() or something, but for this you need to use the mouseenter and mouseleave events directly, the same events .hover() actually binds to.

Nick Craver
gr8 it worked I just need to wait for answer to get accepted. thank you, you got any books to recommend on jquery, how to get better/master it eventually?
Gandalf StormCrow
@Gandalf - I'm not sure, never read any...kinda learned it as I came across something new I needed. A fellow developer read this though, he learned a lot and the reviews seem good as well: http://www.amazon.com/Learning-jQuery-Interaction-Development-JavaScript/dp/1847192505
Nick Craver
+1  A: 

Make sure you are using jQuery 1.4 or later, and according to the docs, you need to use mouseenter and mouseleave rather than hover.

John McCollum