I'm struggling to implement a feature where only one button out of a column of 8 should be toggled yellow at a time, while the rest remain default green. Unfortunately, I can't seem to get the function to execute on click, as none of the colors are changing.
I've been trying to follow a post on How to select and change color of a button and revert to original when other button is clicked as a guide, which has helped me understand querySelectors and changing classes. However, despite my efforts, I can't figure out why my implementation isn't working. When I place Console.log('test')
right after the for loop, it fires, but if I put it below onClick
, it does not.
JS
for (button in buttons) {
buttons[button].onclick = function() {
console.log('test')
var yellowButton = document.querySelectorAll(".yellow")[0];
if (this.className == "green") {
if (yellowButton) yellowButton.className = "green";
this.className = "yellow";
}
}
}
HTML
<button class="green">UPKEEP</button>
<button class="green">DRAW</button>
<button class="green">MAIN</button>
<button class="green">COMBAT</button>
<button class="green">MAIN</button>
<button class="green">END TURN</button>
<button class="green">CLEANUP</button>
CSS
button{
width: 100%;
padding: 10px 20px;
margin: 3px;
}
.green{
background-color: green;
}
.yellow {
background-color: yellow;
}
I'm hoping to achieve a scenario where only one out of the 8 buttons is yellow when clicked.