7

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

Patrissol Kenfack
  • 764
  • 1
  • 8
  • 22
  • @blex no it doesn't because the answers of that question talk about the difference between addEventListener and attachEvent/onclik method whereas I'm talking about executing either of them once – Patrissol Kenfack Mar 02 '20 at 23:31
  • 1
    The once parameter is not supported by all browsers see [docs](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) – Patrissol Kenfack Mar 02 '20 at 23:33

2 Answers2

10

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
});
dmitrydwhite
  • 776
  • 3
  • 11
1

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);
Bryan Elliott
  • 4,055
  • 2
  • 21
  • 22