Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!