Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is jquery event delegation not working?

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 the best practice is to drill as close as possible to the parent element of what I am trying to work with, yet every time I try to do that, I am clearly doing something wrong because my parent level selectors are not working.

like image 964
absentx Avatar asked Jan 04 '13 20:01

absentx


2 Answers

It means that #contain itself is not a static element, you should select closest static parent of the element. Otherwise jQuery doesn't select the element and delegation fails.

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

However, in case that element is static, you are selecting the element too soon, you should wait for DOM to be 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
   });
})
like image 50
undefined Avatar answered Sep 25 '22 10:09

undefined


So, I will try to explain how jquery on(change) works,

if you have

$(document).on('parameter 1','parameter 2', function(){} )

essentially, jquery will check if event mentioned in parameter 1 is executed or not. Then it will check if parameter 2 is present,

if so, Then it will check if the event mentioned in parameter 1 was triggered in the element mentioned in parameter 2. hence you can prevent on(change) events whenever the document changes.

this will help you to bind dynamically loaded elements by making sure the loaded elem has id and then binding events to that id alone. and whenever a document event occurs, the dynamic one will be executed.

like image 37
Faahil B Farouk Avatar answered Sep 24 '22 10:09

Faahil B Farouk