You can create a function that is named only in the scope in which it is executed and, after executing the addEventListener
, call for removeEventListener
to remove it.
Thus:
var button = document.querySelector('#button');
var i = 0;
button.addEventListener('click', function click(e) {
i++;
console.log("Essa função foi chamada %d vez", i);
button.removeEventListener('click', click);
});
<button id="button">Clica aí</button>
That way, unlike using a variable indicating whether the button was clicked or not, the listener of that event will be removed, which can be interesting for performance gain, since you do not need to have a listener since it will no longer do anything.
Addendum:
If you are using jQuery, you can use the method one
to simplify the work:
$('#button').one('click', function (e) {
// Executa somente essa vez, não mais que isso
});
It would be nice if you take a look at these questions:
this wrong it performs more than once the click
– Victor
It calls the function more than 1x, yes! But it only shows "first time" once. The function code should be in the first if (replace the console.log("first time") )
– Raphael Vizoni