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 root34const parent = document.getElementById('parent');5const child = document.getElementById('child');67// Bubbling phase (default)8parent.addEventListener('click', function(e) {9 console.log('Parent clicked (bubbling)');10});1112child.addEventListener('click', function(e) {13 console.log('Child clicked (bubbling)');14 // e.stopPropagation(); // Stop bubbling15});1617// Clicking child will log:18// 1. Child clicked (bubbling)19// 2. Parent clicked (bubbling)2021// Event Capturing (useCapture = true)22// Event flows from root to target2324parent.addEventListener('click', function(e) {25 console.log('Parent clicked (capturing)');26}, true); // true = capturing phase2728child.addEventListener('click', function(e) {29 console.log('Child clicked (capturing)');30}, true);3132// Clicking child will log:33// 1. Parent clicked (capturing)34// 2. Child clicked (capturing)3536// Method 3: Both phases37parent.addEventListener('click', function(e) {38 console.log('Parent - Capturing');39}, true);4041parent.addEventListener('click', function(e) {42 console.log('Parent - Bubbling');43}, false);4445child.addEventListener('click', function(e) {46 console.log('Child - Capturing');47}, true);4849child.addEventListener('click', function(e) {50 console.log('Child - Bubbling');51}, false);5253// Clicking child logs:54// 1. Parent - Capturing55// 2. Child - Capturing56// 3. Child - Bubbling57// 4. Parent - Bubbling5859// Method 4: Stop propagation60child.addEventListener('click', function(e) {61 e.stopPropagation(); // Stop at this element62 console.log('Event stopped');63});6465// Method 5: Stop immediate propagation66child.addEventListener('click', function(e) {67 e.stopImmediatePropagation(); // Stop all handlers68 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