Today I Learned - Rocky Kev

TIL addEventListener's third param

POSTED ON:

TAGS:

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:

  1. 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.
  2. In contrast to using an onXYZ property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
  3. 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:

  1. Get all the 'capture' events first. (2, then 4)
  2. Get all the 'bubble' events. (1, 3)

Via Rob W on StackOverflow

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.