Read more

Efficiently add an event listener to many elements

Henning Koch
September 07, 2010Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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 (event.target) 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.

Examples

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 (event.target.closest('.dialog-link')) {
    // Open dialog
  }
});

Unpoly Show archive.org snapshot

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

jQuery

$(document).on('click', '.dialog-link', function(event) {
  // Open dialog
});
Posted by Henning Koch to makandra dev (2010-09-07 10:03)