Files
30-seconds-of-code/snippets/listen-once.md
2023-04-28 22:29:23 +03:00

680 B

title, type, tags, author, cover, dateModified
title type tags author cover dateModified
Listen for an event only once snippet
browser
event
chalarangelo dog-waiting 2020-10-22T20:23:47+03:00

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