Skip to content

Instantly share code, notes, and snippets.

@akirco
Last active July 25, 2023 12:07
Show Gist options
  • Save akirco/40fcbebb87415015e2862b2452681f59 to your computer and use it in GitHub Desktop.
Save akirco/40fcbebb87415015e2862b2452681f59 to your computer and use it in GitHub Desktop.
listen for an event once
// adds an event listener to ab element that will ibly 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, e, fn) => {
el.addEventListener(e, fn, { once: true });
};
listenOnce(document.getElementById("test"), "click", () =>
console.log("Hello world")
); // 'Hello world' will only be logged on the first click
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment