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?
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>