Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

77
Vistas
how to change class on button click in javascript

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>

7 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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>

7 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.