In JavaScript event handling within the DOM, bubbling and capturing describe how events propagate through nested elements.
💡 Event Propagation Phases
When an event occurs on an element, it goes through three phases:
- Capturing phase: Event travels down from the root to the target element.
- Target phase: Event reaches the actual target element.
- Bubbling phase: Event bubbles up from the target back up to the root.
Capturing vs. Bubbling
| Capturing | Bubbling |
|---|---|
| Event moves from ancestor down to target | Event moves from target up to ancestors |
| Less commonly used | Default phase for event listeners |
Listener’s capture option is true | Listener’s capture option is false or omitted |
| Useful for intercepting events before target | Useful for handling events after target |
💡 Adding Event Listeners with Capturing or Bubbling
Use addEventListener third parameter to specify phase:
element.addEventListener('click', handler, true)– capturing phaseelement.addEventListener('click', handler, false)or omit – bubbling phase
📌 Deep Dive: Event Listener Phases
JAVASCRIPT
const outer = document.getElementById('outer');
const inner = document.getElementById('inner');
outer.addEventListener('click', () => console.log('Outer bubbled'), false);
outer.addEventListener('click', () => console.log('Outer captured'), true);
inner.addEventListener('click', () => console.log('Inner bubbled'), false);
inner.addEventListener('click', () => console.log('Inner captured'), true);
Output when clicking inner
Outer capturedInner captured
Inner bubbled
Outer bubbled
⚠️ Remember:
The default event listener phase is bubbling. Use {capture: true} explicitly to listen during capturing.
Stopping propagation can control the flow:
event.stopPropagation()stops event from moving to other listeners in the same phase and next phases.event.stopImmediatePropagation()also prevents other listeners on the same element from running.
💡 Practical Use Cases
- Capturing: Useful for intercepting events before they reach deeper elements (e.g., global shortcuts).
- Bubbling: Commonly used for event delegation to handle many child elements from a single parent listener.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which phase does an event listener listen to by default?
Question 2 of 2
What does event.stopPropagation() do?
0/2
Loading results...
