Event delegation is a technique in JavaScript where a single event listener is added to a parent element to handle events from its child elements. Instead of attaching event listeners to multiple child elements, you attach just one to the parent and catch events as they bubble up the DOM tree.

Why Use Event Delegation?

  • Improves performance by reducing the number of event listeners
  • Useful for dynamically added elements
  • Cleaner and more maintainable code

How It Works

When an event occurs on an element, it bubbles up through its parent elements. By placing an event listener on a common ancestor, you can capture and respond to those events.


document.getElementById("parent").addEventListener("click", function(event) {
  if (event.target.matches(".child")) {
    console.log("Child clicked:", event.target.textContent);
  }
});

In this example, even if new .child elements are added to the #parent, the event listener will still work.

Real-World Example

Suppose you’re building a to-do list where each item has a delete button:


<ul id="todo-list">
  <li><button class="delete-btn">Delete</button> Task 1</li>
  <li><button class="delete-btn">Delete</button> Task 2</li>
</ul>

document.getElementById("todo-list").addEventListener("click", function(event) {
  if (event.target.classList.contains("delete-btn")) {
    event.target.parentElement.remove();
  }
});

This way, you only need one event listener for all delete buttons—even ones added later with JavaScript.

Benefits of Event Delegation

  • Less memory usage: fewer listeners in the DOM
  • Handles dynamic elements: works with elements added after page load
  • Easier maintenance: one place to manage event logic

Things to Watch Out For

  • Event delegation only works with events that bubble (e.g., click, keyup)
  • Make sure to use event.target wisely to check what was clicked

Conclusion

Event delegation is a powerful and efficient way to manage events in JavaScript. By understanding how event bubbling works, you can write cleaner code, improve performance, and make your applications more dynamic and responsive.

Post a Comment

Your email address will not be published. Required fields are marked *