DEV Community

Cover image for Introduction to Event delegation in JavaScript.
Abhishek Jain
Abhishek Jain

Posted on • Edited on

Introduction to Event delegation in JavaScript.

Hello devs, let's understand event delegation.😁

To understand event delegation, firstly, we'll need to get a hold of how the event listeners work.

Look at the code below.

const sampleDiv = document.getElementById("sampleDiv");
sampleDiv.addEventListener("click", function (event) {
  alert("Sample Div clicked");
});
Enter fullscreen mode Exit fullscreen mode

Woohooo, We've added an event listener.
Things to note in the above code -

  • Browser always provides the event object as a parameter for the callback function.

  • The Event object provides many properties, But we're going to focus on the event.target and event.currentTarget properties.

Let's assume a situation

Suppose a simple todo app.

//HTML
<div id="sampleDiv"></div>
<button id="AddBtn">Add todo</button>
//NOTE: some basic CSS is applied on these elements.

//JavaScript
<script>
  const sampleDiv = document.getElementById("sampleDiv");
  const AddButton = document.getElementById("AddBtn")
  AddButton.addEventListener("click", function (e) {
        let todo = document.createElement("p");
        todo.className = "todoToRemove";
        todo.textContent = "Click me to remove";
        sampleDiv.appendChild(todo);
  });
</script>
Enter fullscreen mode Exit fullscreen mode

And the code above does this -

Todo gif

We want to click on the todo(the paragraph) to remove the todo. so, I think that we can attach event listeners to each todo and remove todo when it is clicked like this-

const Todos = document.getElementsByClassName("todoToRemove");
for (let i = 0; i < notes.length; i++) {
  const element = notes[i];
  element.addEventListener("click", function (e) {
    element.remove()
  });
}
Enter fullscreen mode Exit fullscreen mode

But, It doesn't work.
Since we are adding the todo dynamically through our javascript, the above code runs firstly, but there are no todos so that listeners are attached to any of them.

So, How can we fix this?

Here comes the concept of event delegation. Theoretically, what happens in event delegation is we attach the event listener to a parent element. We check for the event.target property, which results in the actual element on which the event has triggered.

So, the key takeaway is event.currentTarget is the actual element on which the event listener is attached. And, event.target is the element on which the actual event happened.

Fixing the problem with event delegation

We can fix the todo removing problem with this simple code -

sampleDiv.addEventListener("click", (event) => {
   if (event.target.matches("p")) {
      event.target.remove();
   }
});

//NOTE: the remove function have less support on legacy browsers. so, you can also use this line inside if statement - 
event.currentTarget.removeChild(event.target);
Enter fullscreen mode Exit fullscreen mode

And this works perfectly.

Working Example

We added an event listener to the parent and checked if event.target is a p tag. If true, then we call the remove function on it to remove it from the dom tree.

This whole concept of adding an event listener to a parent is called event delegation.

That's it from my side. Till then πŸ‘‹πŸ‘‹

BYE BYE

Top comments (3)

Collapse
 
anantt08 profile image
anantt-08

Kya baat🀩🀩

Collapse
 
crongm profile image
Carlos Garcia β˜…

Thank you for explaining it with a simple and practical approach. :)

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Glad you liked it. :)