0

Mouse hover works at first, but when I click remove button and attach it is not working with mouse hover handler?? why?

thanks.

HTML:

<div id="container">
<button id="a">remove</button><button id="b">attach</button>
<ul>
</ul>
</div>

JS:

    var k = 10; 
        myfunction(k);  
            $('#a').click(function(){   
                $('ul li').remove();    
            });         
            $('#b').click(function(){               
                k = 20;
                myfunction(k);          
            });     
            $('ul li').on('mouseenter',function () {
                var num = $(this).index();
                $('#lit' + num).addClass('currentpage');
                $('#lit' + num).siblings().removeClass('currentpage');
                });

function myfunction(p){
    for(var i=0;i<p;i++){
        $('#container ul').append('<li id=lit'+i+'>Hello'+i+'</li>');
    }
}

Demo: http://jsfiddle.net/JasonHu/8B9VH/5/

akshay
  • 5,811
  • 5
  • 39
  • 58
  • and [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/q/12829963/218196) – Felix Kling Feb 10 '14 at 03:31

3 Answers3

1

You need to use event delegation so that the mouseenter event can be attached to the newly added list item:

$('#container').on('mouseenter','ul li', function() {

});

Updated Fiddle

Felix
  • 37,892
  • 8
  • 43
  • 55
  • It might be helpful to explain why - when the selector `ul li` is executed for the mouseenter handler, it will only find the current `
  • `s inside the `
      `. By using the 2nd argument to `.on()` to specify a selector, you are using the fact that events propagate (bubble) up through the DOM to attach a handler to the `
        ` that is never removed that will check if the original node that triggered the event matches the given selector, which is "li" in this case. This will work for all `
      • `s, regardless of when they were added.
  • – GregL Feb 10 '14 at 03:05