18

I have always used in the past:

$(selector).on('click', function )

But today I was binding this on an object that came in after docready ( from ajax a call ). The binding would not stick.

After googling I saw this:

$(document).on( event, selector, function ) 

syntax. And after changing to this, my code was working.

I have been on a break from jquery and feel like I've missed something, are there a real differences in these 2 methods? What are they?

Is this latter syntax the only way now to do bindings on new elements ( the purpose livequery plugin used to serve ) ?

3

1 Answer 1

23

The first example binds the event listener directly to the elements. It adds a separate listener for each element, and it will only respond to events on elements that were in the DOM at the time the listeners were added.

The second example binds the event listener to the document object. It will check any event that bubbles up to the document object and test to see if the element the event started on matches the selector before firing the function. It doesn't require the elements to exist in the document when the listener is bound. It is possible for the event to be captured (by another listener) and propagation stopped before it bubbles up to the document object.