Event Bubbling vs. Event Capturing in JavaScript: A Complete Guide
Introduction
In JavaScript, understanding event propagation is crucial for handling DOM interactions effectively. Two key phases—event bubbling and event capturing—define how events travel through the DOM tree. Let’s break down these concepts with examples and best practices.
What is Event Propagation?
When an event (e.g., a click) occurs on an element, it doesn’t just trigger on that single element. Instead, it propagates through the DOM in three phases:
- Capturing Phase: Event travels from the root (
window
) down to the target.
- Target Phase: Event reaches the target element.
- Bubbling Phase: Event bubbles up from the target back to the root.
1. Event Capturing (Trickling Down)
2. Event Bubbling (Rising Up)
Key Differences
Feature |
Event Bubbling |
Event Capturing |
Direction |
Bottom → Top |
Top → Bottom |
Default |
Yes |
No (needs true ) |
Use Case |
Event delegation |
Early interception |
How to Stop Event Propagation?
Use event.stopPropagation()
to halt propagation:
element.addEventListener('click', (event) => {
event.stopPropagation(); // Stops bubbling/capturing
});
Practical Example: Event Delegation
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<script>
document.getElementById('list').addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
console.log('Clicked:', e.target.textContent);
}
});
</script>
Why it’s efficient: Attaches one listener to the parent instead of multiple child listeners.