Events and Event HandlingLesson 2.2
What is event bubbling and how does it work
event bubbling, event capturing, propagation phases, stopPropagation, target vs currentTarget
Event Bubbling
When a DOM event fires, it does not stay on the target element. It bubbles upward through every ancestor all the way to document. This is called the bubble phase.
document.querySelector('ul').addEventListener('click', (e) => {
console.log('ul handler fired');
});
document.querySelector('li').addEventListener('click', (e) => {
console.log('li handler fired'); // fires first
});
// Click li → logs: 'li handler fired', then 'ul handler fired'target vs currentTarget
e.target is the element the user actually clicked. e.currentTarget is the element whose listener is currently running.
Stopping Propagation
btn.addEventListener('click', (e) => {
e.stopPropagation(); // bubble stops here
doSomething();
});Capture Phase
Events also have a capture phase that travels from document down to the target before bubbling back up. Enable it with { capture: true } as the third argument. Most code uses the bubble phase — the default.
el.addEventListener('click', handler, { capture: true });Use stopPropagation sparingly. Over-using it makes debugging harder because parent listeners stop firing unexpectedly.
