HomeJAVASCRIPTExplain event delegation.

Explain event delegation.

Event delegation is a technique in JavaScript where instead of attaching event listeners to individual child elements, you attach a single event listener to a parent element. This parent listener can handle events for all of its current and future child elements because of event bubbling in the DOM.


How it Works

  1. An event (like click) on a child element bubbles up through its ancestors.
  2. The parent element’s event listener catches the event.
  3. Inside the listener, you check the event target (event.target) to determine which child triggered the event.

Example Without Event Delegation

// Attaching listeners to each button
document.querySelectorAll('button').forEach(button => {
  button.addEventListener('click', () => {
    console.log(button.textContent);
  });
});

👉 Problem: Inefficient if you have many elements or dynamically added ones.


Example With Event Delegation

// Attach one listener to the parent
document.getElementById('button-container').addEventListener('click', (event) => {
  if (event.target.tagName === 'BUTTON') {
    console.log(event.target.textContent);
  }
});

👉 Here:

  • Only one listener is needed.
  • Works even if new buttons are added dynamically.

Benefits of Event Delegation

  • Performance: Reduces memory usage since fewer listeners are attached.
  • Dynamic Handling: Works for elements added to the DOM later.
  • Cleaner Code: One central listener instead of many scattered ones.

✅ In short: Event delegation leverages event bubbling to handle events efficiently by attaching a listener to a common ancestor rather than each child.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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