Listen for an event only once

JavaScript, Browser, Event · Oct 22, 2020

Adds an event listener to an element that will only run the callback the first time the event is triggered.

  • Use EventTarget.addEventListener() to add an event listener to an element.
  • Use { once: true } as options to only run the given callback once.
const listenOnce = (el, evt, fn) =>
  el.addEventListener(evt, fn, { once: true });
listenOnce(
  document.getElementById('my-id'),
  'click',
  () => console.log('Hello world')
); // 'Hello world' will only be logged on the first click

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Event Handling

    Event handling needs to be done right in JavaScript. Pick up some tips and tricks to create a better user experience.

    Collection · 15 snippets

  • Handle click outside

    Runs the callback whenever the user clicks outside of the specified element.

    JavaScript, Browser · Jan 6, 2021

  • Add multiple listeners

    Adds multiple event listeners with the same handler to an element.

    JavaScript, Browser · Oct 22, 2020

  • Observe element mutations

    Creates a new MutationObserver and runs the provided callback for each mutation on the specified element.

    JavaScript, Browser · Oct 22, 2020