What is the purpose of the third parameter of AddEventListener?

10

When I want to add a listener of some event in Javascript I use addEventListener .

document.addEventListener('click', function (e) {
      alert('clicked');
})

But I noticed that in some codes, a third parameter is used, which I believe to be Boolean . More or less like this:

document.addEventListener('click', function (e) {
      alert('clicked');
}, false)

I read the Mozilla documentation to see what it was about, but I ended up getting more confused by the explanation.

Can anyone clarify me with some example what is the third parameter of addEventListener ?

    
asked by anonymous 29.08.2016 / 14:19

1 answer

16

The third parameter is called capture and defines whether addEventListener should respond to events that descend into the DOM, or go up in the DOM.

Basically, the event traverses two paths when it happens. If you click on an element for example, first the addEventListener that has true in the third argument will be called, from top to bottom in the DOM. Then the addEventListener that has false (or nothing) will be called in the third argument, from the bottom up in the DOM. The event always traverses two paths (if not stopped). It starts at document descends from element to element until it finds the target, and then travels the same path back.

These two phases are called capture phase and bubling phase , respectively capturing phase and ascending phase . The place where it changes is the event.target , that is when the capture phase finds the element that originated the event. What distinguishes at what stage 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>

Event headphones are fired from the top down into the DOM and then from the bottom up. And in this example it is irrelevant to order where they are added.

This argument is useful for making sure that we catch a "firsthand" event in time to prevent its propagation in the DOM. Notice the difference in this version with e.stopPropagation(); : link

In this case the examples of event headers without capture true are not even called.

Learn more in MDN.     

29.08.2016 / 14:27