Event Bubbling and Capturing in JavaScript

Understand event propagation phases

IntermediateEvents ProgramsExample 3 of 10
event-bubbling-and-capturing.js
1// Event Bubbling (default)
2// Event flows from target to root
3
4const parent = document.getElementById('parent');
5const child = document.getElementById('child');
6
7// Bubbling phase (default)
8parent.addEventListener('click', function(e) {
9 console.log('Parent clicked (bubbling)');
10});
11
12child.addEventListener('click', function(e) {
13 console.log('Child clicked (bubbling)');
14 // e.stopPropagation(); // Stop bubbling
15});
16
17// Clicking child will log:
18// 1. Child clicked (bubbling)
19// 2. Parent clicked (bubbling)
20
21// Event Capturing (useCapture = true)
22// Event flows from root to target
23
24parent.addEventListener('click', function(e) {
25 console.log('Parent clicked (capturing)');
26}, true); // true = capturing phase
27
28child.addEventListener('click', function(e) {
29 console.log('Child clicked (capturing)');
30}, true);
31
32// Clicking child will log:
33// 1. Parent clicked (capturing)
34// 2. Child clicked (capturing)
35
36// Method 3: Both phases
37parent.addEventListener('click', function(e) {
38 console.log('Parent - Capturing');
39}, true);
40
41parent.addEventListener('click', function(e) {
42 console.log('Parent - Bubbling');
43}, false);
44
45child.addEventListener('click', function(e) {
46 console.log('Child - Capturing');
47}, true);
48
49child.addEventListener('click', function(e) {
50 console.log('Child - Bubbling');
51}, false);
52
53// Clicking child logs:
54// 1. Parent - Capturing
55// 2. Child - Capturing
56// 3. Child - Bubbling
57// 4. Parent - Bubbling
58
59// Method 4: Stop propagation
60child.addEventListener('click', function(e) {
61 e.stopPropagation(); // Stop at this element
62 console.log('Event stopped');
63});
64
65// Method 5: Stop immediate propagation
66child.addEventListener('click', function(e) {
67 e.stopImmediatePropagation(); // Stop all handlers
68 console.log('All handlers stopped');
69});

Output

// Output depends on which element is clicked

What's going on

Event propagation has two phases.

Bubbling Phase (default)

Event flows from target to root
Bottom-up propagation
Most common use case

Capturing Phase

Event flows from root to target
Top-down propagation
Use third parameter: true

Event Flow

1.Capturing: Root → Target
2.Target: At target element
3.Bubbling: Target → Root

stopPropagation()

Stops event from propagating
Prevents parent handlers

stopImmediatePropagation()

Stops all handlers on element
More aggressive than stopPropagation()

Use Cases

Event delegation
Performance optimization
Complex interactions