dbarnes
dbarnes

Reputation: 1833

Trying to understand the difference between jquery on events

I understand there are a few ways to bind to events in jquery, my concern is over the two ways.

Here is my theoretical markup:

<div id="closerToTheButton">
     <button id="someID"></button>    
</div>

And the possible js options:

$(document).on('click', '#someID', function(){
   // do work
});

And:

$('#closerToTheButton').on('click', '#someID', function(){
       // do work
});

I understand the difference between them if there was a selector other than ID, but is there really a difference in the case of an ID? Is there a performance boost? Which one would be preferred?

Upvotes: 1

Views: 45

Answers (3)

Alnitak
Alnitak

Reputation: 339816

For performance reasons you should always bind to the closest static ancestor (or ancestors) that cover all elements that you want to attach the delegate event handler to.

Upvotes: 0

Leonardo Delfino
Leonardo Delfino

Reputation: 1498

The difference is that applying the click event on the document, it will always be caught if you run this code after the DOM has been created. Now applying the event object # closerToTheButton, it will only be captured if this element exists in the DOM when you execute the code. If it has been dynamically created after running the code, the click event will not be captured.

In matter of performance, the second option is better than the first if you are not dynamically creating the element, because it is not necessary to search for the element # someID throughout the DOM.

Upvotes: 2

mayabelle
mayabelle

Reputation: 10014

Yes, the second option is better for performance, because the event is bound to the #closerToTheButton element rather than the entire document, so only clicks on #someID elements within the #closerToTheButton element will trigger the function. (This is also a slight difference in functionality - if #someID is not a descendant of #closerToTheButton, clicking on it will not fire the function.)

Upvotes: 2

Related Questions