0Pricing
JavaScript Academy · Lesson

Event Delegation Pattern

Handle many child events from one parent listener.

One Listener to Rule Them All

Event delegation means attaching a single listener to a common ancestor instead of many listeners on individual children. Because events bubble, the parent receives clicks from all its descendants.

<ul id="menu">
  <li>Home</li>
  <li>About</li>
  <li>Contact</li>
</ul>

The Naive Approach

Without delegation you would loop over every item and attach a handler. That is wasteful: more memory, and it breaks for elements added later.

document.querySelectorAll("#menu li").forEach((li) => {
  li.addEventListener("click", () => console.log(li.textContent));
});

All lessons in this course

  1. The Capture and Bubble Phases
  2. Event Delegation Pattern
  3. Dynamic Lists with Delegation
  4. Custom Events
← Back to JavaScript Academy