I would like to add a click event listener to a function but would only like it to happen once. How could i do this?
I would like to stay clear of JQuery as well if it is possible please.
EDITED
As the answers that I am getting for this are fully satisfying my need i thought i may make it a bit more clear with context.
I am writing a function to draw a rectangle, first with one click on a button to initiate the rectangle function. Then there are two click event listeners in the drawRectangle function. These are the events i would like to happen only once in the function. Allowing the user to then create another rectangle if they click on the rectangle initiation button again.
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.
There are a number of ways to allow only one-click in Javascript: Disable the button after clicking on it. Use a boolean flag to indicate “clicked”, don't process again if this flag is true. Remove the on-click attribute from the button after clicking once.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
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
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);
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