What you'll learn: By the end of this lesson you will be able to describe the DOM as the tree an event travels through, predict the exact order of listeners for capture, target and bubble, say what
stopPropagation,stopImmediatePropagation,once,passiveandpreventDefaultdo and do not do, and implement event delegation without it breaking on nested elements, late-added items or non-bubbling events.
Picture an apartment block. A courier arrives for flat 4C. The concierge at the front door sees the parcel first, then the floor warden, then the door of 4C is knocked on. Afterwards the news travels back: someone tells the floor warden, then the concierge, that the parcel was delivered. Events in the DOM follow that route: down from the outermost element to the one that was hit, then back up. Event delegation is the concierge saying "send all deliveries for this building to me, and I will check the flat number", instead of a bell and a person at every flat.
This lesson gives the working model of that route and the delegation pattern built on it. The page the events happen on was built by the browser as described in How Browsers Work, and why a long handler blocks the page is in Event Loop and the Main Thread. The lesson builds on HTML, CSS and JavaScript Architecture.
The core idea
- The DOM is a tree, and an event travels along a path in it. The path runs from the root to the element the event was fired on (the
target). - The trip has two passes. The capturing pass goes from the root down to the target, then the bubbling pass goes back up. By default listeners are registered for the bubbling pass; the
captureoption moves one to the capturing pass. targetis where it started,currentTargetis where the running listener is attached.- A listener can stop the walk, cancel the default action, run once, or promise not to cancel. Each of these is a flag on the event or the listener.
- Delegation uses the return trip. One listener on a stable ancestor handles events from many descendants, including ones added later, by looking at
event.target.
Facts about the DOM come from the WHATWG DOM Standard and MDN. The lab uses jsdom 31, which is a JavaScript implementation of the DOM and not a browser.
The path an event takes
Figure 1. A click on a button inside a list item inside a list
How to read this: solid arrows on top are the capturing pass, dashed arrows below are the bubbling pass. The target is where the two meet.
MDN describes the two passes this way: with capture "the event fires first on the least nested element, and then on successively more nested elements, until the target is reached", and with bubbling the event "bubbles up from the innermost element that was clicked". It also notes: "By default almost all event handlers are registered in the bubbling phase."
Illustration 1, the minimal example: four listeners, one click
The lab builds ul > li > button and adds a bubble listener to each, plus a capture listener on the ul. The model is a pure function written from the DOM Standard's dispatch steps, and the demo runs the same scenario on jsdom and checks that both agree:
Expected output, captured from a real run (the bubbling-basic scenario):
=== bubbling-basic
lesson: The path: capture down, then bubble up
tree: ul#ul > li#li > button#button
ul-bubble: click on #ul (bubble)
li-bubble: click on #li (bubble)
button-bubble: click on #button (bubble)
ul-capture: click on #ul (capture)
event: click at #button, bubbles=true, cancelable=true
1. ul-capture currentTarget #ul capturing defaultPrevented=false
2. button-bubble currentTarget #button at target defaultPrevented=false
3. li-bubble currentTarget #li bubbling defaultPrevented=false
4. ul-bubble currentTarget #ul bubbling defaultPrevented=false
dispatchEvent returned true, defaultPrevented false
jsdom agrees with the model: identical
Registration order was ul-bubble first and ul-capture last, yet the capture listener ran first. Order across nodes comes from the path, not from when you called addEventListener.
Two details from the DOM Standard are worth remembering. At the target there is no separate pass: the capture listeners run in the capturing pass and the others in the bubbling pass, so on the target itself capture listeners run first, whatever the order they were added in. And listeners on the same node run in the order they were added: MDN says "they are called in the order in which they were added".
Expected output, captured from a real run (the target-order scenario):
1. button-capture currentTarget #button at target defaultPrevented=false
2. button-bubble currentTarget #button at target defaultPrevented=false
Stopping, cancelling and the listener options
Figure 2. Who gets to run after a listener calls something
later nodes are skipped"] B -->|"stopImmediatePropagation"| D["Rest of this node skipped;
later nodes skipped"] B -->|"preventDefault"| E{"Cancelable and
not passive?"} E -->|"yes"| F["Default action cancelled;
propagation continues"] E -->|"no"| G["Nothing happens"]
How to read this: stopping the walk and cancelling the default are separate. A listener can do either, both or neither.
The DOM Standard checks the stop flag before each node ("If event's stop propagation flag is set, then return"), not after each listener, so stopPropagation does not hide the other listeners on the same node. The lab confirms it:
Lines from a real run of the stop-propagation and stop-immediate scenarios (the setup lines between them are left out, so this is an excerpt, not the whole output):
=== stop-propagation
1. li-first currentTarget #li bubbling defaultPrevented=false
2. li-second currentTarget #li bubbling defaultPrevented=false
=== stop-immediate
1. li-first currentTarget #li bubbling defaultPrevented=false
In both, the ul listener never ran. In the second, MDN's description applies: no remaining listeners will be called, "either on that element or any other element".
Now once, passive and preventDefault. MDN: a once listener "would be automatically removed when invoked", and a passive listener "will never call preventDefault(). If a passive listener calls preventDefault(), nothing will happen". The lab dispatches a click twice:
Expected output, captured from a real run (the once-and-passive scenario):
dispatch 1:
1. once currentTarget #button at target defaultPrevented=false
2. passive-prevent currentTarget #button at target defaultPrevented=false
3. normal-prevent currentTarget #button at target defaultPrevented=true
dispatchEvent returned false, defaultPrevented true
dispatch 2:
1. passive-prevent currentTarget #button at target defaultPrevented=false
2. normal-prevent currentTarget #button at target defaultPrevented=true
dispatchEvent returned false, defaultPrevented true
The once listener ran on the first dispatch only. The passive listener called preventDefault and had no effect; the normal one did, so dispatchEvent returned false. passive also has a default you may not expect: MDN says it defaults to true for wheel, mousewheel, touchstart and touchmove on Window, Document, Document.documentElement and Document.body, so that scrolling need not wait for the listener.
Events that do not bubble
Not every event bubbles. MDN: the focus event "does not bubble, but the related focusin event that follows does bubble", and it offers two ways to delegate it, using focusin or setting useCapture to true. In the lab, a non-bubbling event still reaches a capture listener on the way down, and not a bubble listener on an ancestor:
Expected output, captured from a real run (the non-bubbling scenario):
1. ul-capture currentTarget #ul capturing defaultPrevented=false
2. button-bubble currentTarget #button at target defaultPrevented=false
Event delegation
MDN defines it: "we set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually." The catch is in "have events that happen on them": the handler receives event.target, which may be a span inside the li you care about, or the list itself. Use closest to find the element you want. MDN: closest() "traverses the element and its parents (heading toward the document root) until it finds a node that matches", and it can return the element itself.
Figure 3. The decision a delegated handler makes for each event
finds a match?"} C -->|"no"| X C -->|"yes"| D{"Match is inside
the root, not the root?"} D -->|"no"| X D -->|"yes"| H["Run the handler with
the matched element"]
How to read this: three early exits protect against text nodes, clicks on gaps, and a match that lies above the root, because closest does not stop at your root.
The lab's helper is short:
export function delegate<E extends Event = Event>(
root: Element,
type: string,
selector: string,
handler: DelegatedHandler<E>,
options: { readonly capture?: boolean } = {},
): Delegation {
const listener = (event: Event): void => {
const origin = event.target as Partial<Element> | null;
if (origin === null || typeof origin.closest !== "function") return;
const matched = origin.closest(selector);
if (matched === null || !root.contains(matched) || matched === root) return;
handler(event as E, matched);
};
const capture = options.capture ?? false;
root.addEventListener(type, listener, capture);
return { stop: () => root.removeEventListener(type, listener, capture) };
}
Illustration 2, the realistic example: a product list where items arrive later
A product list shows three items, each with an "Add" button. Per-item listeners are attached once; a fourth item is added afterwards. The delegated version attaches one listener:
Expected output, captured from a real run (jsdom, delegation part):
=== listeners needed, and an item added later
per-item listeners: 3 added; clicking a then d handled ["li[data-id=a]"]
delegated listener: 1 added; clicking a then d handled ["li[data-id=a]","li[data-id=d]"]
=== target, currentTarget and the matched element
event.target = span, event.currentTarget = ul, matched = li[data-id=b]
a click on the list itself: handler ran 0 times (the list is not an li)
The late item d was missed by the per-item code and handled by delegation. The click's target was the span inside the button, currentTarget was the list, and closest recovered the li.
Illustration 3, the failure: something below the root stops the event
Delegation depends on the event reaching the root. If any element in between calls stopPropagation, the delegated handler never hears about it:
Expected output, captured from a real run (jsdom, delegation part):
=== a stopPropagation below the delegating root
delegated handler ran for li[data-id=b]
the click inside li a never reached the list: a stopPropagation below the root hides it
The remedy is the capture option: a delegated listener added with capture: true runs on the way down, before any descendant can stop the event. The lab's test for this passes. The cost is that it sees events the inner handler may then want to swallow.
Trade-offs
| Choice | Gains | Costs |
|---|---|---|
| Per-element listeners | Simple, no closest logic |
One listener per element; late items need wiring |
| Delegation on a stable parent | One listener; late items work | Hidden by stopPropagation below; needs a selector check |
| Capture-phase delegation | Cannot be stopped by descendants | Runs before inner handlers; may act on an event they cancel |
Delegating at document |
One listener for the page | Everything shares one handler; ownership is unclear |
| Passive listeners | Scrolling need not wait | Cannot cancel the event |
Build it: predict the order, then check it
Goal. Predict, then read, the listener order for six scenarios and four delegation cases.
cd examples/frontend/labs/dom-event-propagation
pnpm test # 25 tests
pnpm typecheck
node src/demo.ts # prints both parts
This lab is jsdom, not a browser. jsdom implements the DOM Standard in JavaScript. It has no layout, no real focus handling and no default actions, so focus events are dispatched by hand. The model is checked against jsdom, not against Chrome, Firefox or Safari.
Break it. In src/model.ts, change the capture argument in the capturing loop's call to invoke from true to false. Capture listeners no longer run in the capturing pass and tests fail, including every model-versus-jsdom test. Restore it.
In practice: analytics on a product grid
This is a realistic scenario, not a case history.
The situation
A grid shows product cards with "Add to cart" buttons. Product managers want one analytics event per add. The cards are rendered by a list component that adds and removes items as the user filters.
Starting architecture
Each card attaches its own click handler for add-to-cart. The analytics code is separate and attaches its own listeners to every button after render.
Figure 4. One delegated listener on the grid, in the capture phase
How to read this: the grid outlives its cards, so a listener on it covers cards added later. The solid arrow down is the capturing pass that a descendant cannot stop.
Options considered
| Option | Result | Risk |
|---|---|---|
| Re-attach analytics listeners after each filter | Works | Easy to leak or duplicate |
| One delegated analytics listener on the grid | Late cards covered | Hidden if a card handler stops propagation |
| Delegate in the capture phase | Always sees the click | Fires even if the card then rejects the action |
The decision
One delegated listener on the grid in the capture phase, matching [data-add-to-cart], that records an "attempt". The success event stays in the card's own handler, so a rejected add is not counted as a success.
Rollout and verification
Test with a child handler that calls stopPropagation and assert the analytics listener still fires. Test an item added after attachment.
The 2 a.m. failure
A new quick-view modal lives inside the grid and calls stopPropagation on its close button. The bubble-phase analytics listener goes quiet for that button and nobody notices until a funnel chart drops. The capture-phase listener would have seen the click. The fix is to move the listener to capture and add the stop-propagation test above.
Architect's notes
- Choose one owner for each concern, and delegate on a stable ancestor with a selector, not on
documentby habit. - Treat
stopPropagationas a cost on every ancestor listener, and preferpreventDefaultor a state flag. - Delegate on real interactive elements so keyboard use works the same way.
- Remember that events crossing a shadow root are covered in the lesson on Web Components and Shadow DOM.
Common mistakes
- Reading
event.targetand assuming it is the element you attached something to. - Forgetting that
closestcan match above your root. - Delegating
focuson a bubble listener; usefocusinor capture. - Using
stopPropagationto cancel a default action. - Adding an anonymous function twice and expecting the duplicate to be ignored: MDN notes identical anonymous functions are added again.
Key takeaways
- An event travels root to target, then back up; registration order does not change that.
- On the target, capture listeners run before bubble listeners.
stopPropagationstops later nodes;stopImmediatePropagationalso stops the rest of the node.passivelisteners cannot cancel;oncelisteners remove themselves.- Delegation needs
closest, a root check, and an event that bubbles. - Anything below the root that stops propagation hides the event from a bubble-phase delegate.
Practice exercises
Exercise 1, easy (20 minutes). Run the demo and write down the order for target-order before reading it. Then add a bubble listener on the li and a capture listener on the li and predict again.
Exercise 2, intermediate (45 minutes). Add a scenario with a nested list and delegate on the outer list. Which li does the handler receive for a click in the inner list?
Exercise 3, intermediate (60 minutes). Find a handler in your app that calls stopPropagation. List which ancestor listeners it hides, and replace it with something narrower.
Related reading
- How Browsers Work: where the DOM comes from.
- Event Loop and the Main Thread: why listeners that run long block input.
- Debouncing and Throttling: rate-limiting handlers for events that fire often.
- Memory Management and Leaks: how forgotten listeners keep things alive.
Official documentation
- DOM Standard: dispatching events: the path, the capturing and bubbling passes, the stop flags.
- addEventListener (MDN):
capture,once,passive. - Event bubbling (MDN): capture, bubbling,
target, delegation. - focus event (MDN): why
focusdoes not bubble. - Element.closest (MDN): finding the matching ancestor.
- Responding to events (react.dev): propagation,
onClickCapture,stopPropagationin React.