Lesson 11 of 55 · javascript
Event Propagation – Capturing, Bubbling & `stopPropagation`
Duration: 10 mins
When an event occurs it travels through three phases:
- Capturing – from the
windowdown to the target. - At target – the event reaches the target element.
- Bubbling – back up from the target to
window.
You can control the phase with the third argument of addEventListener:
element.addEventListener('click', handler, true); // capture
Use e.stopPropagation() to halt further propagation, or e.stopImmediatePropagation() to also stop other listeners on the same element.
Example: Stop bubbling
div.addEventListener('click', e => {
e.stopPropagation();
console.log('Div clicked – event will not reach body');
});