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

164
Vistas
Simplifying a javascript color chnaging function

A suggestion in a previous post was to simplify the tedious functions that I have. Here is an example.

function cprChange(){
    compRock.style.backgroundColor = 'gold';
    compRock.style.color = '#414141';
}
function cprChangeBack(){
    compRock.style.backgroundColor = '#414141';
    compRock.style.color = 'white';
}

function cppChange(){
    compPaper.style.backgroundColor = 'gold';
    compPaper.style.color = '#414141';
}
function cppChangeBack(){
    compPaper.style.backgroundColor = '#414141';
    compPaper.style.color = 'white'
}

function cpsChange(){
    compScissors.style.backgroundColor = 'gold';
    compScissors.style.color = '#414141';
}
function cpsChangeBack(){
    compScissors.style.backgroundColor = '#414141';
    compScissors.style.color = 'white'
}

These are for my rock paper scissors games. Basically the user clicks picks rock, paper, or scissors, and I have a computer function that randomly picks one as soon as the user clicks on of their buttons. When the computer chooses, the change functions change the color of the button, and the change back functions return the button to their original color as a user clicks their next button which is rock paper or scissors. To simplify this, I wanted to do something like this.

function colorChange(element){
    element.style.backgroundColor = 'gold';
    element.style.color = '#414141';
}

However when I implement this, it doesn't seem to work. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The easiest way to change colors is through css.

In my case, I just made an .active class that changes the default color when they have an active class. Then with JS I toggle the active class on click.

document.querySelectorAll(".item").forEach(item => {
  item.addEventListener("click", (e) => {
    e.target.classList.toggle("active");
  });
});
.item {
  background-color: #414141;
  color: white;
  padding: 15px;
}

.item.active {
  background-color: gold;
  color: #414141;
}
<div class="rock item active">Rock</div>
<div class="paper item">Paper</div>
<div class="scissors item">Scissors</div>

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