Event Delegation

event delegation
event delegation

Event Delegation is a technique in JavaScript where a single event listener is added to a parent element to handle events for multiple child elements. Instead of attaching listeners to each child, you take advantage of event bubbling to catch events higher in the DOM tree.

💡 Why use Event Delegation?

  • Improves performance by reducing the number of event listeners.
  • Allows dynamic elements added later to be handled without extra code.
  • Simplifies code and maintenance.

How it works: When an event occurs on a child element, it bubbles up to its ancestors. By listening on the parent, you can detect which child triggered the event using event.target.

Event Delegation vs Individual Listeners
Event DelegationIndividual Listeners
One listener on parent handles many childrenEach child has its own listener
Works with dynamic elements added laterListeners must be added for new elements
Better memory and performanceMore memory usage and slower startup

Basic example: A list with many buttons. Instead of attaching a click handler to each button, attach one to the list:

📌 Deep Dive: Delegated Click Handler

JAVASCRIPT
const list = document.querySelector('#button-list');

list.addEventListener('click', (event) => {
  if (event.target.tagName === 'BUTTON') {
    alert(`Clicked button: ${event.target.textContent}`);
  }
});
Output
Alerts the text of the clicked button inside the list

Key points:

  • event.target identifies the actual element clicked.
  • Check event.target matches your selector (e.g., tagName, class).
  • Add listener on a common ancestor, not on individual child elements.

⚠️ Beware of event.target vs event.currentTarget

event.target is the element that triggered the event (e.g., the button clicked).
event.currentTarget is the element the listener is attached to (e.g., the parent).

When to use Event Delegation:

  • Handling many similar child elements (e.g., lists, tables, menus).
  • When child elements are created or removed dynamically.
  • To keep your code cleaner and improve performance.

💡 Summary

Event Delegation leverages event bubbling to efficiently handle events on multiple child elements through a single parent listener, simplifying code and improving performance.