How to add an event for a single click on a function?

I would like to add a click event listener to the function, but I would like it to happen once. How can i do this?

I would like to stay away from jQuery, if possible, please.

edited

As the answers that I get for this, completely satisfy my need, although I can make it more clear with the context.

I am writing a function to draw a rectangle, first with one click of a button, to initiate the rectangle function. Then, in the drawRectangle function, there are two click event listeners. These are events that I would like to do only once in a function. Allowing the user to create another rectangle if they click the rectangle init button again.

+10
source share
6 answers

You should use removeEventListenerafter the event is fired once. However, it removeEventListenertakes a function as an argument, which means that you need to declare a named function, add it with addEventListenerand remove it. Example:

function foo() {
    // do things, then
    removeEventListener('click', foo);
}

addEventListener('click', foo);
+14
source

Use modern JavaScript!

EventTarget.addEventListener("click", function() {

    // Do something cool

}, {once : true});

A logical value indicating that the listener should not be called more than once after adding. If true, the listener will be automatically deleted upon call.

- MDN web documents

Here is a list of browsers that support this feature (90% as of May 2019)

Another link

+19
source
function one(el, type, fn) {
    function handler(event) {
        el.removeEventListener(type, handler);
        fn(event);
    }
    el.addEventListener(type, handler);
}

// use it like
one(window, 'resize', function () {
    alert("This triggers just once");
});

: http://jsfiddle.net/6njpem7x/

+2

Combination of addEventListener and removeEventListener

element.addEventListener("click", clickFunction);
function clickFunction(e) {
    console.log("clicked");
    element.removeEventListener("click", clickFunction);
}

jsFiddle

+1
source

something like that

var el = document.getElementById('something');
el.addEventListener('click', doSomething);

function doSomething() {
  el.removeEventListener('click', doSomething);

  //code
}
+1
source

You can set a cookie after the first click:

document.cookie="click=1; expires=.......";

and add a condition to the listener - if the cookie is set, you will omit this.

-2
source

All Articles