JavaScript Event Delegation

JavaScriptPosted on

1 min read

Event delegation is an efficient way of managing events on multiple elements in JavaScript.

Why Use Event Delegation?

Adding an event to any HTML element is easy; we need the addEventListener() method.

But what happens when we have multiple elements with the same event and functionality? Sure we can use a loop and register individual events, but we will create unnecessary bloat (if we have a lot of items).

How an Event Works?

document.querySelector('button').addEventListener('click', function(event) {
    console.log('click event fired');
});

When we register a click event on a target and trigger it, the following 3 phases happens:

  1. The event goes from the window (our outmost) object to the target element in the capture phase.
  2. In the target phase, the event gets triggered on the clicked element.
  3. The event bubbles up through our target elements’ ancestors back to the window in the bubble phase.

This process is what we call event propagation, the complex process that happens when we dispatch an event (click in this case). This came from the nature of an HTML document where the elements are embedded in each other.

Create Event Delegation

We take advantage of the propagation with event delegation because we always know what element dispatched the event.

  1. First, we set up an event listener on the document (which contains our target). In this example, we capture every click anywhere on our page.
  2. Second, we return if the target is not the wanted element.
document.addEventListener('click', function(event) {
    if (! event.target.matches('.click-me')) return;

    ...
});

In this example, we use matches method, which checks selectors, but you have a lot of options. At the event.target object, you can access anything you need.

See the Pen
JavaScript Event Delegation
by Adam Laki (@adamlaki)
on CodePen.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in JavaScript category