Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an event for a one time click to a function?

Tags:

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.

like image 230
Adam Piper Avatar asked Feb 19 '15 15:02

Adam Piper


People also ask

How do you trigger an event 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 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 make a button clickable 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.

How do I get a click event?

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.


2 Answers

Use modern JavaScript!

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

like image 68
Gibolt Avatar answered Sep 30 '22 16:09

Gibolt


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); 
like image 32
Florian Margaine Avatar answered Sep 30 '22 17:09

Florian Margaine