Event Bubbling and Capturing
When a DOM event fires, it does not stay on the target element — it propagates through the DOM tree in three phases: capturing (top-down), at-target, and bubbling (bottom-up). Understanding propagation is key to writing efficient event handling code.
Bubbling
After an event reaches its target, it bubbles upward through ancestor elements, triggering any matching listeners on each. This is the default phase for addEventListener. Bubbling enables event delegation — attaching a single listener on a parent to handle events from many children.
Capturing
Pass true or { capture: true } as the third argument to addEventListener to listen in the capture phase. Capture listeners fire before the target's own listeners.
Stopping Propagation
event.stopPropagation() prevents the event from travelling further along the propagation path. event.stopImmediatePropagation() also prevents other listeners on the same element from firing.
Event Delegation
Use bubbling to attach one listener on a container and handle events from many children dynamically — this is both more efficient and works for elements added after the listener is attached.