JavaScript - Event Bubbling & Capturing
Overview
Estimated time: 20–25 minutes
Event propagation determines the order in which event handlers are called. Bubbling and capturing are two phases of event flow in the DOM.
Learning Objectives
- Understand event bubbling and capturing.
- Use event delegation for efficient event handling.
Prerequisites
Event Bubbling
document.body.addEventListener('click', function(event) {
console.log('Body clicked');
});
Event Capturing
document.body.addEventListener('click', function(event) {
console.log('Body clicked (capturing)');
}, true);
Event Delegation
document.getElementById('list').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
alert('List item clicked: ' + event.target.textContent);
}
});
Common Pitfalls
- Not all events bubble (e.g.,
blur
,focus
).
Summary
Understanding event propagation is key to advanced event handling and building scalable interfaces.