What's the (document) for?


#1

My question is simple.
Why do we need to put the $(document) in our .on() statements?
What is it telling jQuery?


#2

on() is a method, or more specifically a property meaning it needs an object upon which to base its execution context. In other words, it needs to be bound to an object.

The method is very powerful in that it takes a range of object parameters, or simply a single event parameter list. In its simple form, which we use here, we have,

$(document).on('click', '.item', function(){});

The way the browser heard this event was a click in the document object (meaning it could have been anywhere in the browser window) whence it kicked the method into gear to set about finding where the click actually occured. Having found it occured in an element with a class attribute, "item" it delegated the event to the associated handler, in this case, an anonymous function.

I'll stop here, but we can continue if this subject interests you. It does me, and always deserves more attention than it usually gets.


#3

Why doesn't this work?

$('item').on('click',function() {});

Meaning, why does the " .on " method need a child selector?


#4

I have this crazy idea, but due to other demands can't get to testing it yet...

$('.item').on('click', this, function(){});

No it's not a leap forward, but a step back. It assumes that all of the class='item' elements are present at load time. Any added later will never be bound to this listener.

Theoretically, it should work. If you get to it before me, please post your results. Use any function body that helps to illustrate.


#5

I think I get it!! :smile:
So the " $(document) " statement is a kind of way to make the listener look for new page content?
And the ('click', 'item', function (){...}) tells the event handler which selector will trigger the event. Right?


#6

When we attach an event listener on a parent object, we can specify several types of events and match them to the child element that triggers them, then delegate the event to the appropriate handler. (That should be `'.item', by the way; it is a class selector.)

The listener doesn't actually look for new content, it doesn't need to know or keep track of child elements. They may or may not exist at load time, but the document object does, so makes a suitable binding. When new elements are added, or others are removed the listener doesn't need to be informed. It only listens, then tracks the event back to where it was sent from, and delegates the handler accordingly.