Event Delegation in JavaScript
Event Delegation in JavaScript
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.
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.
Instead of attaching listeners to each item, we attach one listener to the parent
and use event.target to detect which child was clicked.
if (event.target.classList.contains("item")) {
});
✅ Benefits:
Works for dynamically added elements (like items added via JavaScript).
🔹 When to Use Event Delegation?
Use Event
Scenario Why?
Delegation?
Imagine a "Load More" button that adds new items dynamically. Event Delegation
ensures even new items work without adding new listeners.
if (event.target.classList.contains("btn")) {
});
setTimeout(() => {
btn.className = "btn";
document.getElementById("container").appendChild(btn);
}, 3000);
✅ The new button still works without needing extra event listeners!
🔥 Key Takeaways