Events capturing in JavaScript

In addition to the bubbling of events, there is also capturing. In fact, the event first goes from top to bottom (capturing stage), reaches our element (target stage) and only then starts to bubble up (bubbling stage).

In order to hang an event handler taking into account the stage of capturing, there is a third optional parameter in addEventListener. If it is equal to true - the event will fire at the capturing stage, and if false - at the bubbling stage (this is by default). Let's look at an example:

elem1.addEventListener('click', function() { console.log('green - capturing'); }, true); elem1.addEventListener('click', function() { console.log('green - bubbling'); }, false); elem2.addEventListener('click', function() { console.log('blue - capturing'); }, true); elem2.addEventListener('click', function() { console.log('blue - bubbling'); }, false); elem3.addEventListener('click', function() { console.log('red - capturing'); }, true); elem3.addEventListener('click', function() { console.log('red- bubbling'); }, false);

You can check: