What is the event propagation path in the browser?
Every DOM event travels through three phases, and they always happen in the same order. The capture phase starts at the root of the tree and works down towards the target. The target phase happens while the event is on the element that the user actually interacted with. The bubble phase then works back up from the target all the way to the root.
A listener that you register without any options runs during the bubble phase. That is why a click handler on a list item still fires when the user clicks a child element inside that item, because the event bubbles up from the child to the parent. A listener that you register with the capture option set to true runs during the capture phase, which happens first, before the event has even reached the target.
// The DOM only exists in a browser, so check before using it.
if (typeof document !== 'undefined') {
const outer = document.querySelector('#outer');
const inner = document.querySelector('#inner');
outer.addEventListener('click', function (event) {
console.log('outer saw a click on', event.target.id);
});
inner.addEventListener('click', function (event) {
console.log('inner saw a click on', event.target.id);
console.log('current target is', event.currentTarget.id);
});
inner.click();
} else {
console.log('No DOM in this runtime - open a browser console to try it.');
}
Two properties on the event object are worth being able to name in an interview. The target property is the deepest element that the event happened on, so a click on the text inside a button reports the element that holds the text as the target and not the button itself. The currentTarget property is the element whose listener is running right now, and that one changes as the event travels up the tree. Mixing the two up is the cause of a lot of confusing bug reports, so it is worth saying the difference out loud.
Some events do not bubble at all. The focus and blur events do bubble, but the focusin and focusout events were added as bubbling versions of them. The mouseenter and mouseleave events do not bubble either, which is why people often use mouseover and mouseout instead when they need event delegation.