📌 Event Delegation in JavaScript
🚀 What is Event Delegation?
Event Delegation is a technique in JavaScript where a single event listener is
added to a parent element instead of multiple listeners for each child element. This
takes advantage of event bubbling, improving performance and efficiency.
🔹 How Event Bubbling Works (Core Concept)
When an event occurs on a child element, it "bubbles up" through its parent elements.
Event Delegation leverages this bubbling to handle events at a higher level in the
DOM.
📌 Example Without Delegation (Multiple Listeners)
const items = document.querySelectorAll(".item");
items.forEach((item) => {
item.addEventListener("click", () => {
console.log("Item clicked!");
});
});
❌ Problem:
If there are 100+ items, we are adding 100+ event listeners, which is
inefficient.
🔹 Using Event Delegation (Efficient Approach)
Instead of attaching listeners to each item, we attach one listener to the parent
and use event.target to detect which child was clicked.
✅ Example of Event Delegation
document.getElementById("list").addEventListener("click", function (event) {
if (event.target.classList.contains("item")) {
console.log(`Clicked on: ${event.target.textContent}`);
});
✅ Benefits:
Only one event listener is used (better performance).
Works for dynamically added elements (like items added via JavaScript).
🔹 When to Use Event Delegation?
Use Event
Scenario Why?
Delegation?
Many elements need event Reduces memory & improves
✅ Yes
listeners performance
Dynamic elements (added Delegation handles newly added
✅ Yes
later) elements
Few elements, static
❌ No Direct listeners are fine
structure
🔹 Real-World Example: Handling Dynamic Buttons
Imagine a "Load More" button that adds new items dynamically. Event Delegation
ensures even new items work without adding new listeners.
document.getElementById("container").addEventListener("click", (event) => {
if (event.target.classList.contains("btn")) {
alert(`Button ${event.target.textContent} clicked!`);
});
// Dynamically add a new button
setTimeout(() => {
let btn = document.createElement("button");
btn.textContent = "New Button";
btn.className = "btn";
document.getElementById("container").appendChild(btn);
}, 3000);
✅ The new button still works without needing extra event listeners!
🔥 Key Takeaways
✅ Event Delegation improves performance by reducing event listeners.
✅ Uses event bubbling to listen at a higher DOM level.
✅ Works for dynamically added elements, unlike direct event listeners.
Would you like a diagram of event bubbling and delegation? 🚀