Language: EN

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

Event capturing and bubbling in JavaScript

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

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

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

event-phases

Which will respond first?

Which element do you want to react to the click first? And how do we indicate this to JavaScript? This is where the event propagation model comes into play.

This model has three phases:

PhaseExecution Order
CapturingFrom document to 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 pass down to the button. Then, they return back up in the opposite direction to the document.

Let’s see each of them 👇

Event capturing

This is the first phase, in which the event propagates from the root document to the target element.

event-capturing

In our example,

  • The event would move from the root document to the button
  • It would trigger the event handlers of all the intermediate elements in between.

It is less frequently used to capture events than bubbling.

Event bubbling

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

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

event-bubbling

That is, in the example,

  • The event would move from the button to the document
  • Similarly, it would trigger the event handlers of all the intermediate elements in between.

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

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

Capturing in one phase or another

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

To do this, we have a parameter in addEventHandler.

  • true: Capturing.
  • false (or unspecified): Bubbling.

Stopping event propagation

Sometimes, it is necessary to prevent an event from propagating through the DOM, either during the capturing or bubbling phase.

To do this, JavaScript provides two useful methods:

MethodDescription
stopPropagation()Stops the propagation of the event, preventing it from continuing to travel to parent elements.
stopImmediatePropagation()In addition to stopping propagation, it prevents other handlers of the same event from executing on the same element.