For more tips like this, sign up to the weekly newsletter!

Use the "once" option for single-shot event listeners

To add an event listener to an element, use addEventListener(type, listener). The listener function will be called every time the event is fired.

But what if you want it to fire only once?

The trivial solution is to remove the listener with removeEventListener(type, listener), like this:

const listener = () => {
  btn.removeEventListener("click", listener);
  // handle event
};
btn.addEventListener("click", listener);

The obvious downside is that you can no longer use anonymous functions.

Use the {once: true} option

The addEventListener also supports an options object as the third argument. One of its properties is once:

btn.addEventListener("click", () => {
  // handle event
}, {once: true})

This takes care of removing the listener after the first call, so you don't need to do it manually.

Try it
References
Learn more: