Can someone point me towards a solution for the following? I'm trying to find a JS equivalent for this jQuery code:
var formSelector = 'my selector here';
var attribute = 'name';
var formHistory = [];
$(formSelector).one('focusout', function(e) {
formHistory.push(e['target'].getAttribute(attribute));
});
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>
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>
You could use once: true
in the options
parameter passed to addEventListener()
.
Browser support: Chrome 55+, Firefox 50+, Safari 10, Edge 16, IE not supported.
document.getElementById('foo').addEventListener('click', function(e) {
alert('This will be displayed only once.');
}, { once: true });
<button id="foo">Click me</button>
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With