#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
•Question 18 of 50medium

What is Event Bubbling and Capturing?

Understanding event propagation in the DOM.

What You'll Learn

  • Event propagation phases
  • Bubbling vs capturing
  • Stopping propagation

Event Propagation Phases

  1. Capturing - From window down to target
  2. Target - Event reaches the target
  3. Bubbling - From target back up to window

Example

index.htmlHTML
<div id="grandparent">
  <div id="parent">
    <button id="child">Click me</button>
  </div>
</div>
code.jsJavaScript
// Bubbling (default) - bottom to top
document.getElementById('child').addEventListener('click', () => {
  console.log('Child');
});
document.getElementById('parent').addEventListener('click', () => {
  console.log('Parent');
});
document.getElementById('grandparent').addEventListener('click', () => {
  console.log('Grandparent');
});
// Click button: Child → Parent → Grandparent

// Capturing - top to bottom
document.getElementById('grandparent').addEventListener('click', () => {
  console.log('Grandparent');
}, true); // true enables capturing
// Click button: Grandparent → Parent → Child

Stopping Propagation

code.jsJavaScript
element.addEventListener('click', (e) => {
  e.stopPropagation(); // Stops bubbling/capturing
  e.stopImmediatePropagation(); // Also stops other handlers on same element
});

Event Delegation

code.jsJavaScript
// Instead of adding listeners to each button
document.getElementById('buttons').addEventListener('click', (e) => {
  if (e.target.matches('button')) {
    console.log('Button clicked:', e.target.textContent);
  }
});