How can I add an event for a one time click to a function?
function one(el, type, fn) {
function handler(event) {
el.removeEventListener(type, handler);
fn(event);
}
el.addEventListener(type, handler);
}
// use it like
one(window, 'resize', function () {
alert("This triggers just once");
});
Example: http://jsfiddle.net/6njpem7x/
You have to use removeEventListener
once the event is fired once. However, removeEventListener
takes a function as argument, which means you need to declare a named function, add it with addEventListener
, and have it removing itself. Example:
function foo() {
// do things, then
removeEventListener('click', foo);
}
addEventListener('click', foo);
Use modern JavaScript!
EventTarget.addEventListener("click", function() {
// Do something cool
}, {once : true});
A Boolean indicating that the listener should be invoked at most once after being added. If
true
, the listener would be automatically removed when invoked.- MDN web docs
All modern browsers support this feature
Other reference