What is event delegation and how do bubbling and capturing work?
When you click an element, the event travels in three phases:
- Capture: from
windowdown to the target's parent. - Target: at the element that was clicked.
- Bubble: back up from the target to
window.
addEventListener(type, fn) listens in the bubble phase by default; pass { capture: true } for the capture phase. event.stopPropagation() stops the journey; event.preventDefault() cancels the browser default (following a link, submitting a form) and is unrelated to propagation.
Event delegation
Instead of one listener per child, attach one listener to a common parent and use event.target.closest(selector) to find which child was hit.
Benefits: far fewer listeners (less memory), and it works automatically for children added later, such as rows in an infinite list. React itself uses delegation: since React 17 it attaches its listeners to the root container.
Example
<ul id="todo">
<li data-id="1">Buy milk <button class="remove">x</button></li>
<li data-id="2">Call mom <button class="remove">x</button></li>
</ul>
<script>
document.getElementById('todo').addEventListener('click', (e) => {
const button = e.target.closest('button.remove');
if (!button) return; // click was elsewhere
const item = button.closest('li');
console.log('remove', item.dataset.id);
item.remove();
});
</script>Follow-up questions interviewers ask
Try answering each one before you open it.
Which events do not bubble?
focus, blur, mouseenter, mouseleave, load and scroll on elements do not bubble. For delegation use the bubbling versions focusin/focusout and mouseover/mouseout, or listen in the capture phase.