Posted over 10 years ago. Visible to the public. Repeats.

Efficiently add an event listener to many elements

When you need to add a event listener to hundreds of elements, this might slow down the browser.

An alternative is to register an event listener at the root of the DOM tree (document). Then wait for events to bubble up and check whether the triggering element ( matches the selector before you run your callback.

This technique is called event delegation.

Performance considerations

Because you only register a single listener, registering is very fast. The trade-off is that your listener needs to check every event of the registered type, even when they were dispatched on other elements. This makes your listener run slower. This does not matter for low-frequency event types like click, but may matter for high-frequency types like mousemove or scroll.


For the examples below let's assume we have many <a class="dialog-link" ...> elements on our page. Clicking them should open a modal dialog.

Native JavaScript

document.addEventListener('click', function(event) { if ('.dialog-link')) { // Open dialog } });


up.on('click', '.dialog-link', function(event, link) { // Open dialog });


$(document).on('click', '.dialog-link', function(event) { // Open dialog });

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Henning Koch
Last edit:
about 1 month ago
by Henning Koch
event, delegation
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more