Explain event delegation in JavaScript

Answer:

Event delegation in JavaScript is a technique where a single event listener is added to a parent element to manage events for its child elements, even those dynamically added in the future. This approach leverages the concept of event bubbling, where an event propagates from the target element up through its ancestors in the DOM.

How Event Delegation Works:

  1. Attach a single event listener to a parent element.
  2. Use the event object's target property to identify which child element triggered the event.
  3. Perform the necessary action based on the target.

Example:

// HTML
<div id='parent'>
  <button class='child'>Child 1</button>
  <button class='child'>Child 2</button>
</div>;

// JavaScript
document.getElementById('parent').addEventListener('click', function (event) {
  if (event.target.classList.contains('child')) {
    console.log(`Button ${event.target.textContent} clicked!`);
  }
});

Explanation:

Advantages of Event Delegation:

  1. Improved Performance:
  1. Handles Dynamic Elements:

Use Cases:

MDN Web Docs: Introduction to events