JavaScript: remove an event listener from within that listener?

You can pass the once option to have a listener act only once, then remove itself. Docs: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters

Example:

  element.addEventListener('eventname', (ev) => {
    console.log("event is captured only once.");
    // do more stuff...
  }, { once: true });

From the same docs link above, modern browser support is good, but is not available for Internet Explorer.

Leave a Comment