Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

42
Views
Execute part of a button only at the first time?

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>

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs