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
  • 7
    api.jquery.com/on That link will provide all the answers you could possibly need. Commented Nov 17, 2013 at 15:59
  • 2
    There are indeed real differences between the two, and they are thoroughly explained in the documentation Commented Nov 17, 2013 at 16:00
  • 5
    Particularly note the section on Direct and delegated events. Commented Nov 17, 2013 at 16:00

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.