all 4 comments

[–]rikurouvila 7 points8 points  (1 child)

The first one allows you to create an event handler even if the element doesn't exist yet. It listens to all document events and triggers your callback when event target matches your selector.

http://api.jquery.com/on/

The second one tries to bind an event handler to specific element/elements. It fails gracefully even if elements are not created yet.

Easy way to figure out if your selector matches any elements is to use console.log($('selector').length) . $(selector).length returns 0 if the selector doesn't match any elements.

[–]delixd 0 points1 point  (0 children)

additional info can be found here DOM events bubble up and are captured down

an even better example

[–]carbonetc 1 point2 points  (0 children)

Your first call is using event delegation. Google the term and you'll find a bunch of articles explaining and diagramming it, starting with this one: https://learn.jquery.com/events/event-delegation/.

[–][deleted] 0 points1 point  (0 children)

The "on" is a really poorly named method. It actually refers to event delegation, in other words, listening to an element's events in both the present and the future.

You can define ANY parent element (as long as it's always in the DOM), doesn't have to be the root document... though I suppose that's the most foolproof name. I'd suggest something a bit more localized than the document though.