Topic 28 of 37
Event Bubbling, Capturing & Delegation
Overview
When an event (like a click) happens on a deeply nested element, it propagates through the DOM tree. Phase 1 is Capturing (going down the tree). Phase 2 is Target. Phase 3 is Bubbling (going back up the tree). Understanding this allows you to use Event Delegation: attaching a single listener to a parent to handle events for multiple children.
Syntax
event.target refers to the exact element clicked. event.currentTarget refers to the element the listener is attached to (the ul).
Event Delegation Pattern
javascript
// Instead of adding 100 listeners to 100 list items...
// Add ONE listener to the parent ul
const list = document.querySelector('#todo-list');
list.addEventListener('click', (event) => {
// Check if what was actually clicked is what we care about
if (event.target.tagName === 'LI') {
event.target.classList.toggle('completed');
}
});Common Pitfalls
- Overusing stopPropagation(). It can prevent analytics tracking tools or other parent listeners from functioning correctly.
Interview Tips
- If asked how to stop Bubbling, mention `event.stopPropagation()`. If asked how to stop default browser behavior (like a link navigating), use `event.preventDefault()`.
Real-World Example
Handling clicks on dynamically generated elements.
example
javascript
// Because we use delegation, new buttons added later will STILL work!
document.body.addEventListener('click', (e) => {
if (e.target.matches('.delete-btn')) {
deleteItem(e.target.dataset.id);
}
});