Event Bubbling and Capturing

Understand event propagation phases

JavaScriptIntermediate
JavaScript
// Event Bubbling (default)
// Event flows from target to root

const parent = document.getElementById('parent');
const child = document.getElementById('child');

// Bubbling phase (default)
parent.addEventListener('click', function(e) {
    console.log('Parent clicked (bubbling)');
});

child.addEventListener('click', function(e) {
    console.log('Child clicked (bubbling)');
    // e.stopPropagation(); // Stop bubbling
});

// Clicking child will log:
// 1. Child clicked (bubbling)
// 2. Parent clicked (bubbling)

// Event Capturing (useCapture = true)
// Event flows from root to target

parent.addEventListener('click', function(e) {
    console.log('Parent clicked (capturing)');
}, true); // true = capturing phase

child.addEventListener('click', function(e) {
    console.log('Child clicked (capturing)');
}, true);

// Clicking child will log:
// 1. Parent clicked (capturing)
// 2. Child clicked (capturing)

// Method 3: Both phases
parent.addEventListener('click', function(e) {
    console.log('Parent - Capturing');
}, true);

parent.addEventListener('click', function(e) {
    console.log('Parent - Bubbling');
}, false);

child.addEventListener('click', function(e) {
    console.log('Child - Capturing');
}, true);

child.addEventListener('click', function(e) {
    console.log('Child - Bubbling');
}, false);

// Clicking child logs:
// 1. Parent - Capturing
// 2. Child - Capturing
// 3. Child - Bubbling
// 4. Parent - Bubbling

// Method 4: Stop propagation
child.addEventListener('click', function(e) {
    e.stopPropagation(); // Stop at this element
    console.log('Event stopped');
});

// Method 5: Stop immediate propagation
child.addEventListener('click', function(e) {
    e.stopImmediatePropagation(); // Stop all handlers
    console.log('All handlers stopped');
});

Output

// Output depends on which element is clicked

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