Event Delegation in JavaScript

Event Delegation in JavaScript

What?

Event delegation is a pattern to handle events efficiently in JavaScript. The main idea is to reduce the number of event handlers on a webpage and thus improving the performance of the website.

When?

It comes in handy when you have multiple DOM elements present on the page and a group of few elements perform similar actions.

How?

When there are multiple DOM elements present, instead of adding event handlers on each one of them, you can just add one event handler (on the parent/common ancestor element) which can do the exact same work which all those multiple event handlers were supposed to do.

Why?

Multiple event handlers impact the performance of a website. The more event handlers you define, the more memory is used which would result in a decrease in the performance of the website. And this may as well cause memory leaks if not taken care of properly.

Deep Dive

Event delegation makes use of one of the Event Propagation techniques called Event Bubbling. If you are not familiar with Event Propagation, I recommend you to read about it in detail here. But to give you a quick intro - Javascript events do not just occur at the element on which they were performed, rather they travel up and down the HTML DOM tree, starting from the window to the target element and back again to the window. The last phase, when they travel from the target element up to the window, is known as the Event Bubbling phase. In event delegation, we take advantage of this and define a single event listener on a parent element instead of all the individual child elements.

Let's understand this with the help of a simple example. Scenario: Let's say you are designing an HTML Form and there are 3 buttons at the end of the form - Reset, Submit, and Cancel. Instead of defining click event handlers for each of them separately, we can register a single event handler for the parent div encapsulating these 3 buttons and handle the events there when the events bubble up. You can check the event object's target property to gain a reference to the actual button which was clicked. Check the HTML and JS section of the below Codepen to understand this more clearly.

Steps for implementing Event Delegation:

To implement event delegation in your web page, you need to perform the below 3 steps:

  1. Find out the parent element,
  2. Attach the event listener to the parent element, and
  3. Use event.target to find the element on which the action/event was performed

Real Life Scenarios:

Let's see some real-life scenarios where Event Delegation can be useful:

  1. Multiple Links: If a website has multiple navigation links present at the header and you want to log some info about which link was clicked. Instead of defining onclick event handlers on each of the links to log this information, you can define a single onclick handler on the parent like this.
    <ul onclick="logInfo(event)">
     <li><a id="home" href="#">Home</a></li>
     <li><a id="projects" href="#proj">Projects</a></li>
     <!-- some more links -->
    </ul>
    ...
    <script type="text/javascript">
    function logInfo(e) {
     switch(e.target.id) {
         case "home":
             myLogger("'Home' was clicked!");
             break;
         case "projects":
             myLogger("'Projects' was clicked");
             break;
         /* more cases */
     }
    }
    </script>
    
  2. To-Do List: In a simple to-do list application, you generally have edit and delete buttons on each of the list item rows. Similar to the above scenario, instead of defining click handlers on each list item, you can define a single click handler on the parent (ol or ul) and perform the operation based on the type of button clicked (which you can find out from event.target property).
  3. Shopping cart (or similar): Let's say you are creating a cart for your application. Each of the products in the cart can have - and + buttons for decreasing and increasing the quantity of the added products. Instead of registering additional event handlers every time a new product is added to the cart, you can just register a single event handler on the parent element (div or ul).

Summary

Event delegation is a pattern that uses the concept of Event Bubbling to reduce the number of event handlers on a web page by defining a single event handler on a parent element, which in turn increases the performance of the website and prevents memory leaks.

Did you find this article valuable?

Support Shubhaw Kumar by becoming a sponsor. Any amount is appreciated!