Listen for an event only once

Angelos Chalaris · 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

Recommended snippets

  • Handle click outside

    JavaScript, Browser

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

  • Add multiple listeners

    JavaScript, Browser

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

  • Observe element mutations

    JavaScript, Browser

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