JavaScript Event Delegation


What is Event Delegation?

Event Delegation is a technique in JavaScript where you attach a single event listener to a parent element, instead of multiple listeners to individual child elements.

It leverages event bubbling, where events propagate from the child element up to its ancestors.



Example: Without Event Delegation

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
const items = document.querySelectorAll("li");
items.forEach(item => {
item.addEventListener("click", () => {
console.log(item.textContent);
});
});

Problem: If you add more <li> elements later, they won’t have the event listener.



Example: With Event Delegation

<ul id= "list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
const list = document.getElementById("list");
list.addEventListener("click", function (e) {
if (e.target.tagName === "LI") {
console.log("Clicked:", e.target.textContent);
}
});
</script>
  • One event listener for the whole list.
  • Works for existing and future <li> items.


How It Works: Event Bubbling

When you click an <li>, the event bubbles up to the <ul>, where it’s handled.



Dynamic Element Support

const list = document.getElementById("list");
// Add new element dynamically
const newItem = document.createElement("li");
newItem.textContent = "New Item";
list.appendChild(newItem); //  Click event still works due to
delegation


Real-World Use Cases

  • Menus with dynamic items
  • Dropdown lists
  • Form elements
  • Interactive tables (click row to edit)


Best Practice: Use e.target Carefully

list.addEventListener("click", function (e) {
if (e.target.matches("li")) {
// safer than checking tagName
console.log(e.target.textContent);
}
});


Benefits of Event Delegation

Benefit Description
Better Performance Fewer event listeners = faster
Handles Dynamic Content Works with new DOM elements
Cleaner Code Centralized event logic