javascript

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


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.


As the answers that I am getting for this aren't 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.


Solution

  • Use modern JavaScript!

    EventTarget.addEventListener("click", (event) => {
      // 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