Skip to main content

Command Palette

Search for a command to run...

Event Delegation in Javascript

Updated
3 min read
Event Delegation in Javascript
R

A person who is attracted by the world of computer science and very much passionate to learn development.

Introduction

In layman's language, event delegation can be defined as a way to add an event listener to multiple elements with the help of parent elements.

Let’s take an example in real life. We often hear the news that this country's delegation went to another country and made some agreements with different ministries. Now this delegation contains diplomats from different ministries that are our multiple elements and the delegation itself is the parent element Here multiple agreements are our event listeners. These multiple events are made using a single element that is the delegation which is the parent element.

Explanation

Now, if you can relate our event delegation in javascript with a real-life delegation of countries, then it’s simple to understand the concept of event delegation.

Let’s dive into some code for practical understanding. Below is the HTML document with the parent element and its children elements.

<nav class="navbar">
    <ul id="nav_links">
        <li> Home </li>
        <li> About </li>
        <li> Contact </li>
    </ul>
    <button class="nav_login_btn">Login</button>
</nav>

In this example, our nav_links as the parent element and all li tags will be children. Now if we want to add event listeners to each li then we can simply give a class or an id to each li and can access it using querySelector and then can add an event listener explicitly. But we are going to make our life simple. We will only access the parent element and then apply an event listener on it directly. Like the delegation in the above example. And then based on some conditions, we can perform some operations separately on each child.

Let’s take a look at the code.

const list = document.querySelector("#nav_links");// accessed parent element

list.addEventListener("click", (e)=>{  // Added event listener on parent element
    const target = e.target;
    if(target.matches("li")){
            if(target.innerText === "Home"){
                    target.style.color = "red";
                }
            else if(target.innerText === "About"){
                    target.style.color = "blue";
                }
            else{
                    target.style.color = "green";
                }
        }
})

Here matches is the method on the target object which helps to find the child element. It simply returns true or false.

So this is our delegation of the event which performs different operations based on conditions on different elements.

Have a look at the visuals of the above code.

Screen Recording 2022-10-17 at 10.42.23 PM.gif

More Action

We can also perform operations like appending or deleting the child element.

const list = document.querySelector("#nav_links"); // accessed parent element

const newElement = document.createElement("li"); // Created new element
newElement.innerText = "Privacy Policy";         // Added inner text to element

list.addEventListener("click", (e)=>{   // Added event listener on parent element
    const target = e.target;
    if(target.matches("li")){
            if(target.innerText === "Home"){
                    target.style.color = "red";
                }
            else if(target.innerText === "About"){
                    target.style.color = "blue";
                } 
            else{
                    target.style.color = "green";  
          list.appendChild(newElement); // New Element inserted here.
                }
        }
})

Here we are adding a new list element which is the Privacy Policy.

Have a look at the visuals of the above code.

Screen Recording 2022-10-17 at 10.40.01 PM.gif

Summary

So, in this article, we saw how useful event delegation is.

It is basically :

  • A way to add an event listener to multiple elements using a single parent element.
  • It can be used to add child elements or to remove child elements.
  • It has a single event listener on the parent element.
  • Based on different conditions it performs actions on child elements.