0

I have this script but need to have the class to be changed to "go" or "stop". currently I can turn both to change to the class but it should change to one or the other

Code

var form = document.querySelector("form");

form.addEventListener("click", function(event) {
  event.preventDefault();
  const classId = event.target.id;

  if (classId == "go") {
    event.target.className = "go";
  } else if (classId == "stop") {
    event.target.className = "stop";
  }
});
.go {
  background: green;
  color: white;
}

.stop {
  background: red;
  color: white;
}
<form action="">
  <button id="go">GO!</button>

  <button id="stop">STOP!</button>
</form>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Fig
  • 3
  • 2
  • https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript?rq=1 – dokgu Apr 11 '22 at 19:43
  • You are confusing classes and ids throughout your code. –  Apr 11 '22 at 19:43
  • @ChrisG Why do you think so? – Barmar Apr 11 '22 at 19:44
  • You change the `className`, but you don't change the `id`, which you are using to determine what the new `className` and styling should be. – mykaf Apr 11 '22 at 19:47
  • I'm not sure what the desired behavior is here. What are the `.go` and `.stop` classes supposed to be attached to on button click? – M0nst3R Apr 11 '22 at 19:47
  • @Barmar Sorry, did you look at the question? OP wants to toggle classes but sets `id`s, and has a variable called `classId`. It's obvious they don't understand that an id and a class are very different. –  Apr 11 '22 at 19:48
  • Did you notice that there are two buttons? he's toggling the class with `event.target.className = "go";` @ChrisG – Barmar Apr 11 '22 at 19:49
  • @Barmar It is completely unclear what OP is trying to achieve. They could also want both buttons to toggle independently –  Apr 11 '22 at 19:51
  • @ChrisG I think my answer is the only sensible interpretation with the given HTML. If there were a single button toggling between stop and go, that would be different. – Barmar Apr 11 '22 at 19:55

1 Answers1

0

You're adding the class to the clicked button, but never removing the class from the other button.

var form = document.querySelector("form");
const goButton = document.querySelector("#go");
const stopButton = document.querySelector("#stop");

form.addEventListener("click", function(event) {
  event.preventDefault();
  if (event.target == goButton) {
    goButton.classList.add("go");
    stopButton.classList.remove("stop");
  } else if (event.target == stopButton) {
    stopButton.classList.add("stop");
    goButton.classList.remove("go");
  }
});
.go {
  background: green;
  color: white;
}

.stop {
  background: red;
  color: white;
}
<form action="">
  <button id="go">GO!</button>

  <button id="stop">STOP!</button>
</form>
Barmar
  • 741,623
  • 53
  • 500
  • 612