Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only fire an event once?

How do I control only firing an event once?

Actually, a quick Google appears to allude to the fact that .one helps..

like image 707
Qcom Avatar asked Aug 03 '10 05:08

Qcom


People also ask

How do you make an event fire only once?

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.

Which method can be used to handle an event for just only one time?

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.

How do I know if an event listener is working?

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 .


1 Answers

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
like image 197
rofrol Avatar answered Oct 14 '22 11:10

rofrol