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
- The Capture and Bubble Phases
- Event Delegation Pattern
- Dynamic Lists with Delegation
- Custom Events