Event delegation

Understand how event delegation works in the browser and some of it's benefits.

Y ou’ve probably been in a situation in a JavaScript application whereby you’re having to attach click event handlers to a multitude of elements. Using the event delegation pattern, you can prevent this, leading to improved efficiency.

Bubbling

When an event occurs on an element, such as a click, the event propagates upwards through the DOM. This is called event bubbling.

Remember - bubbles always rise to the top.

Event handlers that are attached to any parent elements can listen and react to events on their children.

One thing to be aware of is that focus and blur events do not bubble up through DOM.

Delegate

Based on what we know about bubbling, let’s imagine we have a grand parent element with a parent and a child. We can attach a click event handler to the grand parent element to listen for clicks on the child button.

There are 2 properties available on the event object that contain useful references:

  1. event.target: The element that triggered the event.
  2. event.currentTarget: The element that the event handler was attached to.

<div id="grandParent">
  <div id="parent">
    <button id="child">Click Me</button>
  </div>
</div>
 
<script>
  document
    .getElementById("grandParent")
    .addEventListener("click", function (event) {
      console.log("Clicked element:", event.target); // Logs the button (child)
      console.log("Listening element:", event.currentTarget); // Logs the grandParent div
    });
</script>

Benefits and use cases

The obvious benefits are a reduction in event handlers being attached to elements, resulting in improved memory usage and improved performance.

It’s a great pattern for managing events in menus, forms and tables.

Event delegation also works well with dynamic content. For example, if a new child item is added to the DOM, it’s not necessary to re-attach the event handler - the event will still be triggered if the user clicks on the new item.