You can remove the event listener, after the button gets clicked using removeEventListener
. Do keep in mind that the parameters supplied in the removeEventListener
call must be identical with the ones supplied to the addEventListener
call, otherwise it won't work.
var button = document.getElementById("btn");
button.addEventListener("click", onClick);
function onClick() {
console.log("Clicked");
button.removeEventListener("click", onClick);
}
<button id="btn">Click Me!</button>
If you have added the listener inline (using onClick=""
attribute), you can't use removeEventListener
. You can however remove the onClick
attribute.
var button = document.getElementById("btn");
function onClick() {
console.log("Clicked");
button.removeAttribute("onClick");
}
<button id="btn" onClick="onClick()">Click Me!</button>
You could disable the button, making it un-clickable.
var button = document.getElementById("btn");
button.addEventListener("click", onClick);
function onClick() {
console.log("Clicked");
button.disabled = true;
}
<button id="btn">Click Me!</button>
You can use a Promise
(Promises can only be resolved once).
var button = document.getElementById("btn");
new Promise(function(resolve) {
button.addEventListener("click", resolve);
}).then(onClick);
function onClick() {
console.log("Clicked");
}
<button id="btn">Click Me!</button>
Finally you store the info of whether the button has been clicked or not in a boolean variable.
var button = document.getElementById("btn");
var buttonFlag = false;
button.addEventListener("click", onClick);
function onClick() {
if (buttonFlag) return;
console.log("Clicked");
buttonFlag = true;
}
<button id="btn">Click Me!</button>
Update
You can now also use the once property so that the event only runs once (or never if it's never triggered).
var button = document.getElementById("btn");
button.addEventListener("click", () => console.log("Clicked"), {
once: true
});
<button id="btn">Click Me</button>