Difficulty: Intermediate
Explain event bubbling and capturing in JavaScript. What are the phases of DOM event flow, and how do you control them?
When an event fires on a DOM element, it travels in three phases: capturing from window down to the target's parent, target at the element itself, and bubbling back up from the target to window. Listeners run in the bubbling phase by default; pass { capture: true } (or true) to addEventListener to run during capturing. You can stop the journey with event.stopPropagation().
Say you click a <button> inside <div id="inner"> inside <div id="outer">. The browser computes the propagation path once, then:
event.eventPhase === 1): window, document, html, body, #outer, #inner run their capture listeners, top to bottom.eventPhase === 2): listeners on the button itself run. Since Chrome 89 and in current Firefox and Safari, capture listeners on the target run before bubble listeners, regardless of registration order.eventPhase === 3): #inner, #outer, body, html, document, window run their bubble listeners, bottom to top.Inside any handler, event.target is the element that was actually clicked (the button), and event.currentTarget is the element whose listener is running right now. Confusing these two is the most common bug in delegated handlers.
| Method | What it does |
|---|---|
stopPropagation() | Stops the event moving to the next element; other listeners on the current element still run |
stopImmediatePropagation() | Stops propagation and also skips remaining listeners on the current element |
preventDefault() | Cancels the browser default (form submit, link navigation, checkbox toggle). Has nothing to do with propagation |
Useful listener options: { once: true } removes the listener after one call, { passive: true } promises you will not call preventDefault() (lets the browser scroll smoothly for touchstart and wheel), and { signal } removes the listener when an AbortController aborts.
Not every event bubbles. focus, blur, mouseenter, mouseleave, load, unload and media events like play do not. For delegation you use the bubbling alternatives: focusin and focusout instead of focus and blur, and mouseover and mouseout instead of mouseenter and mouseleave. You can check at runtime with event.bubbles.
Bubbling enables event delegation: attach one listener to a parent and handle clicks from any child using event.target.closest(selector). A Swiggy-style menu with 300 "Add" buttons needs one listener on the list instead of 300, and items added later (infinite scroll, filters) work automatically with no re-binding. React used delegation internally for this reason; since React 17 it attaches its listeners to the root container instead of document.
stopPropagation() "just in case". It breaks analytics, modal close-on-outside-click logic and any delegated handler higher up. Prefer checking event.target instead.event.target when a click lands on a child <span> or <svg> inside the button. Use closest('button').return false stops propagation in addEventListener. It only works in jQuery handlers and inline onclick attributes (where it acts like preventDefault).// HTML: <div id="outer"><div id="inner"><button id="btn">Pay</button></div></div>
const log = (label) => (e) =>
console.log(`${label} (phase ${e.eventPhase}, currentTarget=${e.currentTarget.id})`);
outer.addEventListener('click', log('outer capture'), { capture: true });
inner.addEventListener('click', log('inner capture'), true);
btn.addEventListener('click', log('btn listener'));
inner.addEventListener('click', log('inner bubble'));
outer.addEventListener('click', log('outer bubble'));
btn.click();
Capture listeners fire top down, then the target, then bubble listeners bottom up. eventPhase tells you which phase a handler is running in.
// One listener handles every current and future "Add" button in the menu
const menu = document.querySelector('#menu');
menu.addEventListener('click', (event) => {
// target may be the <svg> icon inside the button, so walk up to the button
const button = event.target.closest('button[data-dish-id]');
if (!button || !menu.contains(button)) return;
addToCart(button.dataset.dishId);
});
// Items rendered later need no extra wiring
menu.insertAdjacentHTML(
'beforeend',
'<li>Masala Dosa <button data-dish-id="42"><svg></svg> Add</button></li>'
);
closest() fixes the classic delegation bug where event.target is a nested icon or span. The contains() check guards against matching a button outside the delegated container.
btn.addEventListener('click', (e) => {
console.log('first handler');
e.stopImmediatePropagation(); // later handlers on btn are skipped too
});
btn.addEventListener('click', () => console.log('second handler')); // never runs
document.addEventListener('click', () => console.log('document')); // never runs
btn.click();
stopPropagation would still let the second handler on the same button run; stopImmediatePropagation cuts off both the remaining handlers and the bubble.
Event Bubbling, Event Capturing, stopPropagation, event.target vs currentTarget, Event Delegation