85

I was trying to find out what is the difference between

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

and

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

I've not been able to find any information on if there is any difference between the two, and if so what that difference may be.

Can someone please explain if there is any difference at all?

Styphon
  • 10,304
  • 9
  • 52
  • 86
  • 2
    Did you read the documentation or do a search on this site. There should be a few million answers to chose from ? – adeneo Feb 14 '13 at 16:16
  • Read about event-delegation in the API-documentation of `.on()`, in [this section](http://api.jquery.com/on/#direct-and-delegated-events) – Christofer Eliasson Feb 14 '13 at 16:17
  • 9
    You'll get "point hungry" hippos answering this, despite the fact that it's clearly documented. The first code says "when the document is clicked, if it's something with the ID of #id then trigger this code". The second one says "when anything that currently exists with the ID of #id is clicked, trigger this code". The first one is for assigning the event to elements that don't exist at that time, but will do in the future. The second one will not fire for any elements added later. – Reinstate Monica Cellio Feb 14 '13 at 16:18
  • 7
    I did do both, but obviously not thoroughly enough. A search is hard because I didn't know what to search for. I wouldn't know what this is called. – Styphon Feb 14 '13 at 16:20
  • 1
    It's explained in the documentation for `on()`. Just quite a bit of reading to do :) – Reinstate Monica Cellio Feb 14 '13 at 16:20
  • 9
    If this should be closed as not constructive or because documentation exists for it, then about 99.9% of stackoverflow questions should be closed, in which case good luck finding the remaining 0.1% as it would probably go out of business. Same goes for the derogatory "point hungry hippos" remark. – cesoid Jul 14 '16 at 15:22
  • @ReinstateMonicaCellio I think this was rather a solid question and actually came up as first when I looked for it on google. Furthermore I agree with Cesoid, but hey, if trashing other people makes you sleep at night, do your thing. – I try so hard but I cry harder May 16 '20 at 12:13

2 Answers2

72

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 1
    I would like to know which one delegates event faster. I want to improve the quality of my jquery code. Since the delegating event from DOM takes little bit time than delegating event from #Element. Please share your thoughts – Arun G Aug 30 '14 at 09:41
  • 1
    @James Allardice - using the latter method, `$(document).on('click', $('#id'), function()...` how can I use `$(this)` to reference `$('#id')`? `$(this)`is currently referencing `document` - which I understand. – cheshireoctopus Sep 17 '14 at 22:24
15

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79