Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
56
rated 0 times [  60] [ 4]  / answers: 1 / hits: 61659  / 9 Years ago, thu, february 19, 2015, 12:00:00

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.


More From » javascript

 Answers
19

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


[#67755] Wednesday, February 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;