What is event bubbling and capturing in JavaScript?
When an event happens on an element, it travels in two phases.
- Capturing: from the top (
window) down to the target. - Bubbling: from the target back up to the top. This is the default for listeners.
parent.addEventListener("click", () => console.log("parent"));
child.addEventListener("click", () => console.log("child"));
// click on child
Output:
Tutorials Class - Output Window
child
parent
To listen in the capturing phase pass true or { capture: true } as the third argument. Stop the travel with event.stopPropagation().
Learn more about the similar topics:
| Tutorials |
|---|
| JavaScript Events |
| JavaScript HTML DOM |
| JavaScript DOM Manipulation |
| JavaScript HTML DOM EventListener |
| JavaScript Forms and Validation |
| Exercises & Assignments |
|---|
| Write a JavaScript program to change the text of a paragraph on button click |
| Write a JavaScript program to switch dark mode on and off |