JavaScript, Today I Learned
Handling an Event Callback Once
Learn how to simplify your code by using a simple trick to remove an event listener after an event has been fired once.
Archived writing, published in 2020. I’ve fixed some grammar since, but otherwise it’s as I wrote it, so some details may have aged.
An interesting tidbit I stumbled upon recently is the ability to remove an event listener once it’s called.
In the past, I would have added an event listener to an element and then removed it within the callback function. It would have looked something like this:
const button = document.querySelector("button");
button.addEventListener("click", function onClick() {
console.log("clicked");
button.removeEventListener("click", onClick);
});
In this example, an event listener is attached to the button element, and once clicked, the listener is removed.
This code can be cleaned up by passing one additional argument to the event
listener, { once: true }.
const button = document.querySelector("button");
button.addEventListener(
"click",
function onClick() {
console.log("clicked");
},
{ once: true },
);
This example works exactly like the one above, except it requires less code. Less code means fewer potential bugs to fix later 😁.