What is the false for at the end? Thanks.
window.addEventListener('load', function() { alert("All done"); }, false);
addEventListener("click", first, true); when clicking child element, first method will be called before second . By default, the useCapture flag is set to false which means you handler will only be called during event bubbling phase.
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
addEventListener listens for both capture phase and bubbling phase events. The third parameter (called useCapture in the specification) allows the programmer to specify which phase they want to use.
The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers. Syntax: element.
I checked MDN too, but I still didn't understand what the useCapture
was for, so this answer is for those who still don't get it after having checked the official documentation.
So first of all, the following happens in almost all browers:
In all browsers, except IE<9, there are two stages of event processing.
The event first goes down - that’s called capturing, and then bubbles up . This behavior is standartized in W3C specification.
which means no matter what you set the useCapture
to, these two event phases always exist.
This picture shows how it works.
According to this model, the event:
Captures down - through 1 -> 2 -> 3.
Bubbles up - through 3 -> 2 -> 1.
Then comes your question. The 3rd param called useCapture
indicates on which of the two phases you want your handler to handle the event.
useCapture = true
The handler is set on the capturing phase. Events will get to it before getting to its children.
useCapture = false
.The handler is set on the bubbling phase. Events will get to it after getting to its children.
which means that if you write code like this:
child.addEventListener("click", second); parent.addEventListener("click", first, true);
when clicking child element, first
method will be called before second
.
By default, the useCapture
flag is set to false which means you handler will only be called during event bubbling phase.
For detailed info, click this reference link and this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With