Event Bubbling and Capturing (JavaScript)

Bubbling

Event bubbling is a mechanism in which an event triggered on a specific element propagates through its parent elements in the DOM hierarchy, triggering their respective event handlers.

So, here is an example of bubbling:

How to stop bubbling?

A bubbling event goes from the target element straight up. Normally it goes upwards till <html>, and then to document object, and some events even reach window, calling all handlers on the path.

But any handler may decide that the event has been fully processed and stop the bubbling. The method for it is event.stopPropagation().

Capturing

Capturing refers to the phase in which an event is first propagated from the outermost ancestor element towards the target element during event propagation. During this phase, event handlers attached to the ancestor elements are executed before the event reaches the target. It allows capturing the event's occurrence and performing actions or modifications at higher levels of the DOM hierarchy before reaching the actual target element.

The standard DOM Events describes 3 phases of event propagation:

  1. Capturing phase – the event goes down to the element.

  2. Target phase – the event reached the target element.

  3. Bubbling phase – the event bubbles up from the element.

We often forget about the capturing phase because it's rarely used.

To catch an event on the capturing phase, we need to set the handler capture option to true:

elem.addEventListener(..., {capture: true})

// or, just "true" is an alias to {capture: true}
elem.addEventListener(..., true)