Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Bubbling and capturing are the two 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 two event listeners, one on the 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 ancestors, 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',
() => {
// capturing phase
},
true
)
Note that first all capturing event handlers run, then all the bubbling event handlers.
The order follows this principle: the DOM goes through all elements from the Window object down to the item that was clicked. While doing so, it calls any event handler associated with the event (capturing phase).
Once it reaches the target, it then goes back up the tree to the Window object, calling the event handlers again (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 |
| 12: | Keyboard Events |
| 13: | Mouse Events |
| 14: | Touch Events |
| 15: | Form Events |