Browser events: Bubbling and capturing

Bubbling and capturing are the 2 models that DOM events use to propagate.

Suppose your DOM structure is

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

You want to track when users click on the button, and you have 2 event listeners, one on button, and one on #container.

Remember, a click on a child element will always propagate to its parents, unless you stop the propagation (see later).

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

Bubbling means that the event propagates from the item that was clicked (the child) up to all its parent tree, starting from the nearest one.

In our example, the handler on button will fire before the #container handler.

Capturing is the opposite: the outer event handlers are fired before the more specific handler, the one on button.

By default all events bubble.

You can choose to adopt event capturing by applying a third argument to addEventListener, setting it to true:

document.getElementById('container').addEventListener(
  'click',
  () => {
    //window loaded
  },
  true
)

Note that first all capturing event handlers are run.

Then all the bubbling event handlers.

The order follows this principle: the DOM goes through all elements starting from the Window object, and goes to find the item that was clicked. While doing so, it calls any event handler associated to the event (capturing phase).

Once it reaches the target, it then repeats the journey up to the parents tree until the Window object, calling again the event handlers (bubbling phase)

Lessons in this unit:

0: Introduction
1: Handling events
2: The `DOMContentLoaded` event
3: The `event` object
4: Mouse events
5: Keyboard events
6: `preventDefault()`
7: Stopping event propagation
8: ▶︎ Bubbling and capturing
9: Form submit event
10: Input fields events
11: Creating custom events
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!