Understanding Event Delegation in JavaScript

Understanding Event Delegation in JavaScript

Event Delegation in JavaScript is an important optimization technique that we can use to make our websites run faster when responding to user-events. It saves us memory, and can help make our code simpler and easier to write and understand.

In this article, I’ll discuss how you, as a web developer, can optimize the addition of event listeners in all these situations by employing a technique called event delegation.

Event Delegation

Generally, on our webpage, we have a lot of events that handle everything, like click, keyup, input, mouse events, a lot of random events.

When our application grows, we need to add more events if we are following the same approach, and then the number of events keeps increasing and our web app keeps getting loaded with lots of events handlers.

At some point in time, it causes performance issues and our web app will be slower.

For example:

Suppose we have a webpage with five categories and all five categories are attached with event handlers. When we clicked on a category then an alert box will be opened with information. We can perform anything on this click, like redirecting to a separate webpage, console, call a function, etc.

Let’s see the code implementation for the above scenario. Write the below code in a file index.html and open it in the browser.

index.html:

<!DOCKTYPE HTML>
<html>
  <head>
    <title>Event Bubbling</title>
  </head>
  <body>
    <div class="container">
      <ul id="fruits">
        <li id="apple">Apple</li>
        <li id="banana">Banana</li>
        <li id="guavava">Guavava</li>
        <li id="greps">Greps</li>
       <li id="orange">Orange</li>
    </ul>
  </body>

  <script>
    // Bind an event listener for apple.
    var apple = document.querySelector('#apple');
    apple.addEventListener('click', (event) => {
      console.log("Apple clicked");
      alert("Apple clicked");
    });
    // Bind an event listener for Banana.
    var apple = document.querySelector('#banana');
    apple.addEventListener('click', (event) => {
      console.log("Banana clicked");
     alert("Banana clicked");
    });
    // Bind an event listener for Guavava.
    var apple = document.querySelector('#guavava');
    apple.addEventListener('click', (event) => {
      console.log("Guavava clicked");
      alert("Guavava clicked");
    });
    // Bind an event listener for Greps.
    var apple = document.querySelector('#greps');
    apple.addEventListener('click', (event) => {
      console.log("Greps clicked");
      alert("Greps clicked");
    });
    // Bind an event listener for orange.
    var apple = document.querySelector('#orange');
    apple.addEventListener('click', (event) => {
      console.log("Orange clicked");
      alert("Orange is 250/- per KG");
    });
  </script>
</html>

Let’s open this file in the browser: This is image title

Great, it works fine... But what is the problem in our above code?

There is no problem in our code, but the problem is that we have five <li> elements and we have attached five event handlers to it.

What if, in the future, our categories increase to N? Will we write N event handlers?

Also in this code:

  • Can we remove some code?

  • Can we remove some event handlers and achieve what we want?

  • Can this task be done by writing less code instead?

  • Can we optimize the code?

The answer is: “Yes, we can.” We can write less code and achieve what we want by using event delegation.

Event delegation is, instead of attaching event handlers to each and every child element or the HTML elements individually, we will attach an event directly to its parent element. So, due to event bubbling in JavaScript, this is possible, event delegation can be done.

What will be the change after attaching the event to its parent element? The event happening is that the child element will propagate (bubble up) to its parent and the attached event handler of the parent will listen and the handler function will be invoked.

Let’s implement this into our code. We will make some changes to our index.html, so now our index.html will have the following code:

<!DOCKTYPE HTML>
<html>
  <head>
    <title>Event Delegation</title>
  </head>

  <body>
    <div class="container">
      <ul id="fruits">
        <li id="apple">Apple</li>
        <li id="banana">Banana</li>
        <li id="guavava">Guavava</li>
        <li id="greps">Greps</li>
        <li id="orange">Orange</li>
      </ul>
    </body>
  <script>

    // Bind an event listener to parents which is fruits.
    var apple = document.querySelector('#fruits');
    apple.addEventListener('click', (event) => {
      console.log(event.target.id + " clicked");
      alert(event.target.id + " clicked");
    });
  </script>
</html>

Now, we can see in the above code that I have removed all the event handlers from the previous code and written just one event handler to the parent element, which is fruits.

And this event handler does the same things that all five previous handlers were doing separately.

Let’s open this file (index.html) in the browser and see the result.

This is image title Optimized ( event delegation ) code execution

This is how we can optimize our code using event delegation and improve code quality.

Pros and Cons of Event Delegation

Pros

  • Code quality: We can improve our code quality and maintenance would be easy.

  • Memory: Having more events in our code will take a lot of memory, and using event delegation we will save memory.

  • Performance: The event delegation will improve the performance of the app.

  • DOM manipulation: If we implement the event handlers on each and every child element and we have infinite scroll, then every time the child element gets added dynamically, the DOM will update every time. Using event delegation, DOM manipulation will be less.

Cons

  • Not all events bubble up. There are some events that are not bubbled up like blur, focus, window resizing, or scrolling. In this case, using event delegation would be tough.

  • The child stops propagation. Sometimes, HTML elements stop doing event propagation using stopPropagation(). In this case, the event propagation will be stopped and will not be bubbled up in the hierarchy.

Conclusion

The conclusion is that we need not attach event handlers to all the child elements. Instead, we can attach only one event handler to its parent and handle the function for achieving the goals.

Learn More

Thanks for reading.

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.