Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
Call back a function to change the div color after click on button + click on div

hello everyone. I'm strugling to do some piece of code with 2 different buttons colors that when clicked, they change the color value so when I click the div it changes to that color. I found that I can do it the first time but I can not call again the function to repeat the process all over again. Any suggestions? Thank you a lot :)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
.green {
  background-color: green;
}

.red {
  background-color: red;
}

#change {
  border: 1px solid black;
  width: 500px;
  height: 500px;
}
 
 </style>
  </head>
  <body>
<div id="change"></div>
<button id="green-btn">Green</button>
<button id="red-btn">Red</button>
 
    <script>

  const gbutton = document.getElementById("green-btn");
  const rbutton = document.getElementById("red-btn");
  const change = document.getElementById("change");
  let color = "";
  
  
  function changeGreen () {
    color = "green";
  }
 
  
  function changeRed () {
    color = "red";
  }
 
  gbutton.addEventListener("click", changeGreen)
  rbutton.addEventListener("click", changeRed)

  change.addEventListener("click", () => { 
   
    if(color == "green") {
      change.classList.add("green");
    } else if (color == "red") {
      change.classList.add("red");
    }});


   </script>
  </body>
</html>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

you just have to remove other class

change.addEventListener("click", () => {
  console.log('color', color)
  if (color == "green") {
    change.classList.add("green");
    change.classList.remove("red");
  } else if (color == "red") {
    change.classList.add("red");
    change.classList.remove("green");
  }
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

you should remove the other class

change.classList.add("green")
change.classList.remove("red")
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda