need that javascript function to only runs once [closed]

You shouldn’t use inline JavaScript. Not only it makes your code less maintainable but it makes attaching and detaching events much harder.

What you should do is to fetch the target element from the DOM and attach a click handler to it. To be able to detach it later, the click handler can’t be an anonymous function, so define it separately.

Later on you can attach the listener that will be executed when you click the element. If you want to run it only once, you can use the click handler to detach the handler itself afterwards. See example (in the context of an event handler ‘this’ refers to the DOM element itself)

var button = document.getElementById("clickme");
var clickHandler = function(e) {
    alert("clicked");
    this.removeEventListener("click", clickHandler);
}
button.addEventListener("click", clickHandler);

Here’s a working example
http://codepen.io/anon/pen/xAjnG/?editors=101

To extend it further, if you want the button to be active not once but a number of times, you can keep a counter. Note you can use this general case and set limit = 1.

var button = document.getElementById("clickme");
var counter = 0;
var limit = 3;
var clickHandler = function(e) {
alert("clicked " + ++counter);

    if(counter >= limit) {
        this.removeEventListener("click", clickHandler);
    }
}

button.addEventListener("click", clickHandler);

Here’s a working example
http://codepen.io/anon/pen/mzjcC/?editors=101

Leave a Comment