Event Phases Run Capture Then Bubble
A click travels down from window to the target during capture, then bubbles back up; listening in the wrong phase changes which handlers run.
Code
// 页面结构:<div id="outer"><div id="inner"><button id="action">go</button></div></div>
// 事件传播分三段:capture(捕获)从 window 向下到 target,然后 bubble(冒泡)向上
// addEventListener 第三个参数 true = 捕获阶段监听;默认 false = 冒泡阶段
const log = [];
const outer = document.querySelector('#outer');
const inner = document.querySelector('#inner');
const button = document.querySelector('#action');
outer.addEventListener('click', () => log.push('outer bubble'), false);
outer.addEventListener('click', () => log.push('outer capture'), true);
inner.addEventListener('click', () => log.push('inner bubble'), false);
inner.addEventListener('click', () => log.push('inner capture'), true);
button.addEventListener('click', () => log.push('button target'), false);
button.click();
console.log('order:', log.join(' > '));
// stopPropagation:inner 的冒泡监听器里调用后,outer 的冒泡监听器不再收到事件;
// 但传播是先到 target 再冒泡,button 的监听器在此之前已经执行
inner.addEventListener('click', (e) => e.stopPropagation(), false);
log.length = 0;
button.click();
console.log('stopped:', log.join(' > '));How it works
Top-level bindings log, outer, inner, button hold the demo state — nothing sits inside a function scope.
What to watch for
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Using it
The demo output is labeled (order:, stopped:), so every printed line maps back to its originating operation.
Key statements
button.addEventListener('click', () => log.push('button target'), false);
outer.addEventListener('click', () => log.push('outer bubble'), false);
outer.addEventListener('click', () => log.push('outer capture'), true);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does Event Phases Run Capture Then Bubble run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.