Introduction to Event delegation in JavaScript.
Tags: html, javascript, beginners, tutorial
Published: 2020-12-19 11:14:12

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.

```javascript
const sampleDiv = document.getElementById("sampleDiv");
sampleDiv.addEventListener("click", function (event) {
  alert("Sample Div clicked");
});
```

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.

```javascript
//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>
```

And the code above does this - 

![Todo gif](https://media.giphy.com/media/ZSifZ5G2qOjiOrwwuj/giphy.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-

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

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 - 

```javascript
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);
```

And this works perfectly.

![Working Example](https://media.giphy.com/media/rSw1ENoaCJgxLNoerE/giphy.gif)

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](https://media.giphy.com/media/7DzlajZNY5D0I/giphy.gif)