.on() in jquery


i dont get why i have to put "click" instead of ".click()" because an event is supposed to go in there, isn't it? that's an event name.
or are you supposed to put the "event name"?

thanks have a nice day! :smiley:


Hey Tommy,

Try it with click() instead - it won't work. The reason for that is, if you do this:

$('.item').click(function() {
  // ...

then when script.js loads, it looks for all elements with the item class and listens for clicks on them. The problem with that is that there are no .items when the page loads - they're added by the user afterwards.

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

listens for clicks anywhere on the page (document), then checks if they're on an element with the item class. Since it's listening for clicks anywhere and then checking them, it works but the other doesn't.

Make sense? :slightly_smiling:


oh that really helped me, but i was talking about something else

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

why can't i put '.click()' instead of 'click' because putting '.click()' makes more sense to me
or is it just the syntax or some kind of rule that we have to put the "event handler name" in the event parameter?

thanks a lot though!! :grin:


Oh, I see what you were asking :slightly_smiling:
click() is a jQuery function you call on an element to add a click event listener to it.
click is an event name.

Since they're different things, you can't really swap them out. I'm not aware of any reasons other than that for why you can't use .on('.click()', ...).

Does this answer your question? :slightly_smiling:


yup i get it now
thank you!!