TIL addEventListener's third param
POSTED ON:
TAGS: javascript click mdn
First, I just learned about this new heads-up in the MDN docs!
The addEventListener()
method is the recommended way to register an event listener. (Over onclick)
The benefits are as follows:
- It allows adding more than one handler for an event. This is particularly useful for libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries or extensions.
- In contrast to using an onXYZ property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
- It works on any event target, not just HTML or SVG elements.
Now that we're in agreement, here's the syntax:
addEventListener(type, listener, options);
addEventListener(type, listener, useCapture);
What is useCapture
? #
Events can be activated at two occasions: At the beginning ("capture"), and at the end ("bubble").
document.body.addEventListener("click", () => console.log(1), false);
document.body.addEventListener("click", () => console.log(2), true);
document.body.addEventListener("click", () => console.log(3), false);
document.body.addEventListener("click", () => console.log(4), true);
// it'll execute in
// 2, 4, 1, 3
The sequence of events is:
- Get all the 'capture' events first. (2, then 4)
- Get all the 'bubble' events. (1, 3)
What is options
? #
If you send true/false, it's a useCapture
.
If you send a object... (wink emoji)
Now we're in options land!
document.body.addEventListener("click", () => console.log(1), { once: true });
// all the options
document.body.addEventListener("click", () => console.log(1), {
capture: false, // same as useCapture
once: true, // fires only once
passive: true, // if true, this listener will ignore preventDefault()
signal: true, // removes the listener if it spots a AbortSignal abort() method.
});
MDN - EventTarget.addEventListener() - addEventListener third param
Related TILs
Tagged: javascript