4 min read
ā¢Question 18 of 50mediumWhat 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
- Capturing - From window down to target
- Target - Event reaches the target
- 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 ā ChildStopping 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);
}
});