Issue
Without jQuery, I would like to execute a specific part of a button BUTTON
only the first time one clicks it, which means the specific code won't execute after one has clicked the button, while the rest of the button's code works as usual. How do I do this?
let btn = document.getElementById("btn");
let num = document.getElementById("num");
function add(){
num.innerHTML++;
//specific code (+5 the first time one clicks the button)goes here please//
}
btn.addEventListener("click",add);
<button id="btn">BUTTON</button>
<span id="num">0</span>
<p> first click the button would add 5 to the number, then it will only add 1 each time. </p>
Solution
Use a variable that remembers whenever the button has been clicked.
let btn = document.getElementById("btn");
let num = document.getElementById("num");
let btnClicked = false;
function add() {
if (!btnClicked) {
num.innerHTML = +num.innerHTML + 5;
btnClicked = true
} else {
num.innerHTML++;
}
}
btn.addEventListener("click", add);
<button id="btn">BUTTON</button>
<span id="num">0</span>
Answered By - Reza Saadati
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.