The Difference Between Capturing and Bubbling Phase in JavaScript

Event bubbling and capturing are two ways events can be handled in the HTML DOM API. When an event occurs in an element and its parent also registers a handle for the same event, the event propagation model will determine which element should receive the event first.

By default,Β addEventListenerΒ uses bubbling β€” here the event is first captured in the innermost element and propagates to outer elements:

const ul = document.getElementById('parent');
const li = document.getElementById('child');

// Because of event bubbling, this will return β€œπŸ‘Ά, πŸ‘¨β€
ul.addEventListener('click', () => console.log('πŸ‘¨'));
li.addEventListener('click', () => console.log('πŸ‘Ά'));
bubbling.js
Copied to clipboard!

While in the capturing phase, the opposite happens. The event is captured in the outermost element first and propagates to inner elements:

// Because of event capturing, this will return β€œπŸ‘¨, πŸ‘Άβ€
ul.addEventListener('click', () => console.log('πŸ‘¨'), true);
li.addEventListener('click', () => console.log('πŸ‘Ά'), true);
capturing.js
Copied to clipboard!

As you can see, you can change the even propagation mode for addEventListener, by setting the second parameter (useCapture) to true.

You can check out the differences at the following pen, change the flag to use bubbling instead of capturing:

What is the difference between event delegation and bubbling?
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript in 5 hours.
JavaScript Course
50 JavaScript Interview Questions

Resources:

JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less than 5 hours.

Learn More

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Read more on
Ezoicreport this ad
πŸŽ‰ Thank you for subscribing to our newsletter. x