Capturing
Capturing
Section titled “Capturing”Introduction
Section titled “Introduction”The capturing phase is the first phase of event propagation. Events travel from the document down to the target element before bubbling back up.
Visual Explanation
Section titled “Visual Explanation”flowchart TD A["document"] B["<html>"] C["<body>"] D["<div>"] E["<button> ★ Target"]
A -->|"1. Capture phase ↓"| B B -->|"2. Capture phase ↓"| C C -->|"3. Capture phase ↓"| D D -->|"4. At target"| EUsing Capture Phase
Section titled “Using Capture Phase”// Pass { capture: true } to listen during capture phasedocument.querySelector('div').addEventListener('click', () => { console.log('Div — capturing phase!');}, { capture: true });
document.querySelector('button').addEventListener('click', () => { console.log('Button — at target');});
// Clicking the button logs:// 'Div — capturing phase!' ← capture runs first// 'Button — at target'
// Shorthand: pass true instead of { capture: true }parent.addEventListener('click', handler, true);When to Use Capturing
Section titled “When to Use Capturing”- Events that don’t bubble (focus, blur, mouseenter)
- Intercepting events before they reach the target
- Global event monitoring/debugging
Summary
Section titled “Summary”- Capturing phase: document → target (downward)
- Set
{ capture: true }or passtrueas third argument - Capturing listeners run before bubbling listeners
- Useful for events that don’t bubble