Skip to content
Advertisement

Start/Stop button not working as expected

I have recently started learning JavaScript, and I’d like to make a button, with a function, which changes the innerHTML on click. On the first click it changes the text, but after that nothing. Any ideas how could I fix that? Here is the code so far:

let Button = document.getElementById("Btn");

Button.onclick = function change() {

  let turnedOn = false;
  if (Boolean(turnedOn) == false) {
    Button.innerHTML = "START";
    turnedOn = true;
  } else {
    Button.innerHTML = "STOP";
    turnedOn = false;
  }
}
<Button id="Btn">STOP</button>

Advertisement

Answer

You have to set the turnedOn flag outside of the click method, otherwise it will always be false on click.

Also you’re setting the flag turnedOn inside the if-else statement in a reversed way.

Note: As you are only changing the text, you can use textContent

const button = document.getElementById("btn")
let turnedOn = false

button.addEventListener('click', e => {
  if (turnedOn) {
    turnedOn = false
    e.currentTarget.textContent = 'Start'
  } else {
    turnedOn = true
    e.currentTarget.textContent = 'Stop'
  }
})
<button id="btn">Start</button>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement