How do I control only firing an event once?
Actually, a quick Google appears to allude to the fact that .one
helps..
Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
Using once() Sometimes you want your application to respond to an event (or type of event) only one time (i.e., the first time the event occurs). To do this, Node provides the once() method. It is used just like the addListener() and on() methods, but allows for responding to the event only once.
To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .
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!"); });
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