Number One will connect the click event to the elements that exist when this statement is executed. For example, the handler is directly tied to the actual elements that correspond when this call is made.
Number 2 will attach the click event to the document and upon receiving any clicks it checks whether the element that was actually clicked matches any of the specified selectors and if this will trigger the handler. This is more of an event than a simple connection.
So this means a few things:
- Using number two, clicks on the elements that you add later will call the handler; with number one they will not.
- Only bbbling events, such as
click , work with number two (because it relies on an event bubbling the DOM to the document level). - If you use a delegated handler (number two), and another code captures the event on the actual element, and then cancels the propagation (bubbles) of the event, the delegated handler will not see it.
- The delegated form (number two) should correspond to the element that was pressed (and, possibly, its ancestors), against the selector when clicked, which takes a non-zero time interval. Not necessarily a lot of time, but more than a direct handler (which should not do this). If you have many delegated handlers on the same element (in this case, on the document), you can start to notice.
There are times when it is better to use a handler with a direct connection, and times when delegating events (usually using something more focused than document ), however. Usually the dividing line between them is a decision call, but, for example, if you want to respond to clicks on the rows of the table, you are probably better off not attaching the click event to the table element using the tr selector, rather than attaching the click event for each individual row of the table , especially if you are dynamically updating the table. If you have a unique button that you know in the DOM when you attach a handler, and you want to run a specific function when that button (but not something else) is clicked, a direct handler probably makes more sense.
Here is an example ( live copy ):
HTML:
<p>Click me</p>
JavaScript:
jQuery(function($) { $('p').on('click', function() { display("Directly-attached handler fired. Click this paragraph and note the difference in what happens compared to when you click the 'click me' paragraph."); }); $(document).on('click', 'p', function() { display("Delegated handler fired."); }); function display(msg) { $("<p>").html(msg).appendTo(document.body); } });
Note that when you click the βclick meβ paragraph, you get two new paragraphs added to the document, one of which is the result of the first call to on , and the second is the result of the second. But keep in mind that if you press either of these two new paragraphs, you will only see the handler of the second on call (delegated), not the first. This is because these paragraphs did not exist when you connected the first handler.
source share