event-bubbling-y-event-capturing-en-javascript

Event capturing and bubbling in JavaScript

  • 5 min

The event model in JavaScript is based on a propagation system that allows events to travel from parents to children and vice versa through the document structure.

It’s important to understand this model to control the order in which DOM elements respond to an event.

For example, when we click a button inside a form, we are clicking both the form and the button.

event-phases

Which one will respond first?

Which element do you want to react to the click first? And how do we tell JavaScript? This is where the event propagation model comes in.

This model has three phases:

PhaseExecution Order
CapturingFrom document to the target
TargetOn the target itself
BubblingFrom the target to document

The target is the lowest element in the DOM that receives the event.

That is, events occur in the document and travel down to the button. Then, they make the journey back in the opposite direction, back to the document.

Let’s look at each one 👇

Event capturing

This is the first phase, where the event propagates from the root document towards the target element.

event-capturing

In our example,

  • The event would move from the root document towards the button
  • It would trigger the event handlers of all intermediate elements along the way.

It is less frequently used for capturing events than bubbling.

Event bubbling

In this phase, the event propagates from the target element towards the document.

This phase occurs after the capturing phase and allows parent elements to handle events generated by their child elements.

event-bubbling

That is, in the example,

  • The event would move from the button towards the document
  • Similarly, it would trigger the event handlers of all intermediate elements along the way.

This is the default phase in most browsers and is the one commonly used in event handling.

Not all events support bubbling, but most do (for example, click does, but focus does not).

Capturing in one phase or the other

DOM events always go through these phases. And we can choose in which phase we want to respond to the event.

For this, we have a parameter in addEventHandler.

  • true: Capture.
  • false (or unspecified): Bubble.

Stopping event propagation

Sometimes it’s necessary to prevent an event from propagating through the DOM, whether during the capture or bubble phase.

For this, JavaScript provides two useful methods:

MethodDescription
stopPropagation()Stops the event propagation, preventing it from traveling further to parent elements.
| `stopImmediatePropagation()` | In addition to stopping propagation, it prevents other handlers for the same event from executing on the same element. |
Copied!