back to blogs
Event Delegation in JavaScript

Waleed Ahmad / Sep 12, 2025
2 min read

What is Event Delegation?
Event delegation is a JavaScript technique where instead of adding an event listener to every child element, you add one listener to a common parent and let events “bubble up” through the DOM.
Why is it useful?
- Improves Performance - Fewer event listeners
- Cleaner Code - Centralized event handling logic
- It's more efficient than adding event listeners to each element.
Let's look at the example and understand the problem first.
So we have 3 boxes and a button to add more boxes
<body>
<button>Create Box</button>
<div class="parent">
<div class="box">Static Box 1</div>
<div class="box">Static Box 2</div>
<div class="box">Static Box 3</div>
</div>
</body>
when a box is clicked we want to add the "clicked" class to the box to change the background color of the box
.clicked {
background-color: lightblue;
}
How people typically handle this
// Selecting Elements
const parent = document.querySelector(".parent");
const boxes = document.querySelectorAll(".box");
const button = document.querySelector("button");
// When the button is clicked, create a new box
button.addEventListener("click", () => {
const newBox = document.createElement("div");
newBox.innerText = "Dynamic Box";
parent.append(newBox);
});
// Attach a separate click event listener to each box
boxes.forEach((box) => {
box.addEventListener("click", () => {
box.classList.toggle("clicked");
});
});
Now let's see the problem first
Click the Create Box button to add a few new boxes. Now try clicking both the original (static) boxes and the ones you just created (dynamic). Notice how the background color changes only for the static boxes — the dynamic ones don’t respond.
Let’s fix it with event delegation.
- Instead of adding a click listener to every single box, we attach one listener to the parent container.
- When a box is clicked, the event bubbles up to the parent, where we check if the clicked element is a box and handle it.
parent.addEventListener("click", (e) => {
if (e.target.classList.contains("box")) {
e.target.classList.toggle("clicked");
}
});
This time, try clicking both the static and dynamic boxes. You’ll see that the background color changes for every box, no matter when it was created.