Only fire an event once?
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
You can use jQuery's one
method, which will subscribe to only the first occurrence of an event.
For example:
$('something').one('click', function(e) {
alert('You will only see this once.');
});
Same as rofrol's answer, just another form:
function addEventListenerOnce(element, event, fn) {
var func = function () {
element.removeEventListener(event, func);
fn();
};
element.addEventListener(event, func);
}