• ...">

    Why doesn't jquery event delegation work?

    I have the following html:

    <ul id="contain"> <li class="active_one"></li> <li class="two"></li> </ul> 

    And the following jquery:

     $contain = $('#contain'); //going to use a lot $contain.on('click','li.two', function(){ console.log('working'); //plus do other stuff }); 

    The above does not work, but when I change it to:

     $('body').on('click','li.two', function(){ console.log('working'); //plus do other stuff }); 

    Then it works, but I know that the best practice is to drill as close as possible to the parent element of what I'm trying to work with, but every time I try to do this, I obviously do something wrong, because my parent selectors level do not work.

    +4
    source share
    1 answer

    This means that #contain itself is not a static element, you must select the nearest static parent element. Otherwise, jQuery does not select the item and delegation is not performed.

    Event handlers are bound only to the currently selected elements; they must exist on the page when your code makes a .on () call.

    However, if this element is static, you select the element too quickly, you have to wait until the DOM is ready.

     $(document).ready(function(){ var $contain = $('#contain'); //going to use a lot $contain.on('click','li.two', function(){ console.log('working'); //plus do other stuff }); }) 
    +11
    source

    All Articles