Event delegation is a technique where you attach one event listener to a parent element instead of multiple listeners on each child, and handle events based on which child was actually clicked.
🔹 What Is Event Delegation?
Instead of this ❌:
button1.addEventListener("click", handler);
button2.addEventListener("click", handler);
button3.addEventListener("click", handler);
We do this ✅:
parent.addEventListener("click", handler);
This works because of event bubbling.
🧠 How Event Delegation Works
- User clicks a child element
- Event fires on the child
- Event bubbles up to the parent
- Parent listener catches it
🔍 How Do We Know Which Element Was Clicked?
We use:
✅ event.target
parent.addEventListener("click", (event) => {
console.log(event.target);
});
event.target→ actual element clickedevent.currentTarget→ element with the listener (parent)
🧪 Example
HTML
<ul id="list">
<li data-id="1">Item 1</li>
<li data-id="2">Item 2</li>
<li data-id="3">Item 3</li>
</ul>
JavaScript
document.getElementById("list").addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
console.log("Clicked:", e.target.textContent);
console.log("ID:", e.target.dataset.id);
}
});
🧠 What happens?
- User clicks
<li> - Event bubbles to
<ul> e.targettells which<li>
🔥 Real-World Use Cases
✔ Large lists (tables, menus)
✔ Dynamic elements (added later)
✔ Better performance
✔ Cleaner code
⚠️ Common Mistakes
❌ Using event.currentTarget instead of event.target
❌ Not checking element type
❌ Stopping propagation unnecessarily
🎯 Short Interview Answer
Event delegation is a pattern where a single event listener is attached to a parent element to handle events for its child elements using event bubbling.
We identify the clicked element usingevent.target, which refers to the actual element that triggered the event.
⭐ One-line summary
Event delegation uses bubbling and event.target to efficiently handle events for multiple elements.