πŸŽ„ Get 20% off from our JavaScript course for the holidays! πŸŽ„
The Difference Between Capturing and Bubbling Phase in JavaScript

The Difference Between Capturing and Bubbling Phase in JavaScript

Ferenc Almasi β€’ Last updated 2020 October 26 β€’ Read time 1 min read
  • twitter
  • facebook
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:

Copied to clipboard! Playground
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

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

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

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

50 JavaScript Interview Questions

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended