When you click a button or interact with elements on a webpage, JavaScript handles these events in a specific order called event propagation. Two important concepts here are event bubbling and event capturing. Knowing how these work helps you write better event handlers and avoid common pitfalls.
In this blog, we’ll explain event bubbling and capturing with simple examples.
🧠 What is Event Propagation?
When an event occurs on a DOM element, it doesn’t just affect that element. Instead, the event travels through a path consisting of three phases:
- Capturing phase – event moves from the window down to the target element.
- Target phase – event reaches the target element.
- Bubbling phase – event bubbles back up from the target to the window.
📚 Event Capturing
Event capturing happens first — the event goes down the DOM tree to the target element. By default, most event handlers don’t listen during this phase unless you explicitly specify.
javascriptCopyEditdocument.getElementById('parent').addEventListener('click', () => {
console.log('Parent clicked during capturing');
}, true); // true enables capturing
📚 Event Bubbling
Event bubbling happens after the target phase — the event bubbles up the DOM tree to parent elements.
javascriptCopyEditdocument.getElementById('parent').addEventListener('click', () => {
console.log('Parent clicked during bubbling');
}, false); // false or omitted means bubbling
🧪 Example
htmlCopyEdit<div id="parent" style="padding: 20px; background: lightblue;">
Parent
<button id="child">Click Me</button>
</div>
javascriptCopyEditdocument.getElementById('parent').addEventListener('click', () => {
console.log('Parent clicked');
});
document.getElementById('child').addEventListener('click', (e) => {
console.log('Button clicked');
// e.stopPropagation(); // Uncomment to stop bubbling
});
Output when clicking button:
cssCopyEditButton clicked
Parent clicked
The event bubbles up from the button to the parent.
🔧 Stopping Propagation
To prevent the event from bubbling or capturing further, use:
javascriptCopyEdite.stopPropagation();
This can be useful when you want to handle an event exclusively on a specific element.
💡 Why It Matters
- Avoid unintended multiple event triggers.
- Manage event handling on parent vs child elements.
- Improve performance by delegating events properly.
Conclusion:
Event bubbling and capturing are fundamental to how JavaScript handles DOM events. Mastering them helps you build efficient, bug-free interactive web apps.
🔥 Pro Tip: Use event delegation with bubbling to handle events efficiently on dynamic elements.