My approach to event delegation
Some folks like to add listeners near the top of the DOM tree: on the
I used to do this, but now I prefer to attach the listener to the closest common ancestor. I don’t use jQuery, but their documentation for the
on() method says that this is the best approach:
Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of
document.bodyfor delegated events on large documents.
Given the following HTML, imagine that when one of the three paragraphs is clicked, I want to log its
textContent to the console:
Instead of attaching my listener to the
document.body, I’d attach it to the
main element, since that’s the closest common ancestor:
I’m not saying you should never add event listeners close to the top of the DOM tree. If you have lots of event handlers in many different places, it’s quicker, easier, and more performant to do it that way.
But if you only need to listen for an event at a specific part of the DOM, it makes sense to move your listener further down the tree 👍
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!