Event bubbling and event delegation
EasyDOMEvents
What are event bubbling and capturing, and what is event delegation?
TL;DR
A DOM event travels in three phases: capturing (from window down to the target), target, and bubbling (from the target back up to window). Listeners run in the bubbling phase by default. Event delegation uses bubbling: instead of a listener on every child, you put one listener on a common parent and check event.target to see which child was hit.
Key points
- Delegation means fewer listeners and less memory, and it works for children added later without re-binding.
- Use
event.target.closest('selector')to find the relevant element, since the click may land on a nested child (an icon inside a button). event.targetis where the event started;event.currentTargetis the element the listener is on.stopPropagation()stops the event from moving further. Use it sparingly: it breaks delegation and analytics higher up.preventDefault()is different: it cancels the browser's default action (following a link, submitting a form).- Some events don't bubble (
focus,blur,mouseenter); usefocusin/focusoutinstead.
Example
js
document.querySelector('#todo-list').addEventListener('click', (event) => {
const button = event.target.closest('button[data-action="delete"]')
if (!button) return
deleteTodo(button.dataset.id)
})Common follow-ups
- How do you listen in the capturing phase?
addEventListener('click', fn, { capture: true }). - Does React use delegation? Yes. React attaches its listeners to the root container and dispatches to your components itself.
What interviewers look for
Tip
The three phases, the delegation benefits (fewer listeners, dynamic children), and closest() for nested targets.
- Red flag: confusing
stopPropagationwithpreventDefault.