Chapter XXIV · Advanced Concepts

Event Delegation

Event delegation is a pattern where a single event listener is attached to a parent container to manage events triggered on its child elements.

01 How It Works

Think of a security guard at a main building entrance monitoring visitors entering any room inside.

Relying on event bubbling, events propagate up from target child elements to parent handlers, reducing memory usage.

example.js
document.getElementById("parent-list").addEventListener("click", function(event) {
  if (event.target && event.target.matches("li.item")) {
    console.log("List item clicked:", event.target.textContent);
  }
});
  1. 1. Attach an event listener to a common parent element.

  2. 2. Inspect event bubbling origin via `event.target`.

  3. 3. Handle events dynamically for current and future child elements.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
document.querySelector(".menu").addEventListener("click", e => {
  if (e.target.tagName === "BUTTON") {
    console.log("Button clicked:", e.target.dataset.action);
  }
});

Key Takeaway

Event delegation optimizes performance and handles dynamically added elements efficiently.

Related Concepts