JavaScriptMedium
What is event delegation?
Event delegation is attaching one event listener to a common ancestor instead of to each child, and using event.target (usually with closest()) to work out which child the event came from; it relies on events bubbling up.
Why use it
- Fewer listeners: one listener for a list of 1,000 items instead of 1,000.
- Dynamic content just works: items added later are handled automatically, with no need to attach new listeners.
- Less cleanup: nothing to remove when items are deleted, which also avoids leaks.
How to do it well
- Listen on a stable parent (the list, table or container).
- In the handler, find the relevant element with
event.target.closest(selector). This handles clicks on nested elements, like an icon inside a button. - Check that the found element is inside your container (
container.contains(el)). - Read what to do from
data-*attributes (data-action="delete",data-id="42").
Limitations
- Only works for events that bubble (use
focusin/focusoutinstead offocus/blur). - If a child calls
stopPropagation(), the parent never sees the event. - Very frequent events (
mousemove) on huge containers can do more work per event than targeted listeners.
Frameworks
React attaches listeners at the root of the app and dispatches to components, which is delegation done for you.
Code example
js
1document.body.innerHTML = `2 <ul id="todos">3 <li data-id="1">Write docs <button data-action="done">✓</button> <button data-action="delete">✕</button></li>4 <li data-id="2">Fix bug <button data-action="done">✓</button> <button data-action="delete">✕</button></li>5 </ul>`;6const list = document.getElementById("todos");7const events = [];89// ONE listener for every current and future item10list.addEventListener("click", (event) => {11 const button = event.target.closest("button[data-action]");12 if (!button || !list.contains(button)) return;13 const item = button.closest("li");14 const { action } = button.dataset;15 events.push(`${action} #${item.dataset.id}`);16 if (action === "delete") item.remove();17 if (action === "done") item.style.textDecoration = "line-through";18});1920// Items added later work automatically21list.insertAdjacentHTML("beforeend", `<li data-id="3">Ship it <button data-action="delete">✕</button></li>`);2223list.querySelector('[data-id="1"] [data-action="done"]').click();24list.querySelector('[data-id="3"] [data-action="delete"]').click();25console.log(events, list.children.length); // ["done #1", "delete #3"] 2
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.