JS equivalent for jQuery one()
Update
In most browsers you can now pass in once: true
in an options object:
document.getElementById('btn').addEventListener('click', () => {
console.log('Hello and goodbye');
}, {
once: true,
});
<button id="btn">Click me</button>
Old way
In the eventlistener callback, just destroy the event listener :) Here's a helper function:
function oneTimeEvent(element, eventType, callback) {
element.addEventListener(eventType, function(e) {
e.target.removeEventListener(e.type, arguments.callee);
return callback(e);
});
}
var btn = document.querySelector('button');
oneTimeEvent(btn, 'click', function () {
alert('♫ You clicked me once, but I won\'t let you click me twice, yeah!');
});
<button>Click me!</button>
Here's a really simple solution using data attributes.
document.querySelector('#click').addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
alert('clicked');
})
<button id="click">Click me</button>