How to bind an event listener only once in pure JavaScript?

Viewed 10033

I already know the Jquery solution

$('#myid').one('click', function(event) {
  ...
});

But now I'm finding the Pure JavaScript way because I'm not using Jquery

I have checked the once option but it is not supported by all browsers see the docs

2 Answers

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

You can pass the third argument, an options object, with { once: true }

At the bottom, you'll notice it doesn't work for IE :(

const myElement = document.getElementById('my-element-id');

myElement.addEventListener('click', function namedListener() {
  // Remove the listener from the element the first time the listener is run:
  myElement.removeEventListener('click', namedListener);

  // ...do the rest of your stuff
});

Inside the event listener function, you can then remove the event listener, like so:

document.getElementById("myid").addEventListener("click", handler);

// handler function
function handler(e) {
    // remove this handler
    e.target.removeEventListener(e.type, arguments.callee);

    alert("This event will fire only once!");
}

Edit: Although the above solution works, as mentioned in the comments, arguments.callee has been depreciated, and can throw errors when using use strict;, therefore an alternative solution would be like this:

// handler function
var eventHandler = function(e) {
  // remove this handler
  e.target.removeEventListener('click', eventHandler, false);

  alert("This event will fire only once!");
}

document.getElementById("myid").addEventListener("click", eventHandler);
Related