Use once
if you don’t need to support Internet Explorer:
element.addEventListener(event, func, { once: true });
Otherwise use this:
function addEventListenerOnce(target, type, listener, addOptions, removeOptions) {
target.addEventListener(type, function fn(event) {
target.removeEventListener(type, fn, removeOptions);
listener.apply(this, arguments);
}, addOptions);
}
addEventListenerOnce(document.getElementById("myelement"), "click", function (event) {
alert("You'll only see this once!");
});
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
- http://www.sitepoint.com/create-one-time-events-javascript/
- https://www.webreflection.co.uk/blog/2016/04/17/new-dom4-standards