The third parameter is called capture
and defines whether the addEventListener
must respond to events that descend in the DOM, or rise in the DOM.
Basically the event goes through two paths when it happens. If you click on an element for example, first the addEventListener
who have true
in the third argument, from top to bottom in the DOM. Then the addEventListener
who have false
(or nothing) in the third argument, bottom to top in the DOM. The event always goes two ways (if not stopped). It starts in the document
descends from element to element to find the target, and then goes the same way back.
These two phases are called capture Phase and bubling Phase, respectively capture phase and ascension phase. The place where changes is the event.target
, that is when the capture phase finds the element that originated the event. What distinguishes at what stage the addEventListener
is triggered is that third argument capture
.
A practical example would be:
function logCaptura(e) {
console.log(this.tagName, 'fase de captura');
}
function logBubble(e) {
console.log(this.tagName, 'fase de bubling');
}
document.querySelector('section').addEventListener('click', logCaptura, true);
document.querySelector('div').addEventListener('click', logCaptura, true);
document.querySelector('button').addEventListener('click', logCaptura, true);
document.querySelector('section').addEventListener('click', logBubble);
document.querySelector('div').addEventListener('click', logBubble);
document.querySelector('button').addEventListener('click', logBubble);
<section>
<div>
<button type="button">Clica-me!</button>
</div>
</section>
The event headphones are shot from top to bottom in the DOM and then from bottom to top. And in this example is irrelevant to the order in which they are added.
This argument is useful to make sure we catch an event "first hand" and in time to prevent its spread in the DOM. Notice the difference in this version with a e.stopPropagation();
: https://jsfiddle.net/kqLkdk3c/
In this case the event headphones examples without the capture true
are not even called.
More information on MDN.
Wallace: The answer was what you were looking for?
– Sergio
@Sergio I usually take a little while to mark them. Thanks for reminding me (without wanting to abuse, I think you will always need to warn me)
– Wallace Maxters
You do well to wait, in this case I was just curious if something was missing.
– Sergio