Event bubbling and event capture

Explore how event bubbling and event capture work in JavaScript

Bubbling and capture are the two models used for propagation of DOM events.

Assuming your DOM structure is

<div id="container">
  <button>Click me</button>

You want to track when a user clicksbutton, You have 2 event listeners, one on the button and one on the#container.

Remember that clicking on a child element will always propagate to its parent element unless you stop propagation (see below).

These event listeners will be called in order, and this order is determined by the event bubbling/capturing model used.

BlisteringIndicates that the event propagates from the clicked item (child item) to all its parent trees, starting from the nearest tree.

In our example,buttonWill be at#containerProcessing procedures.

CaptureOn the contrary: the external event handler is triggered before the more specific handler,button.

By default, all events will bubble.

You can choose to adopt event capture by applying the third parameter toaddEventListener, Set it totrue:

  () => {
    //window loaded

noteRun all capture event handlers first.

Then there are all bubbling event handlers.

The order follows this principle: the DOM traverses all elements starting from the Window object, and then finds the item that was clicked. When doing so, it will call any event handlers associated with the event (capture phase).

Once it reaches the target, it will repeat the process of traversing the parent tree until the Window object, and call the event handler again (bubbling phase)

Download mine for freeJavaScript beginner's manual

More js tutorials: