I have a column of 8 buttons and would like only one button to be toggled(yellow) at a time and the rest of the buttons remain default(green). I am having a bear of a time getting the function to execute on click. Meaning no colors are changing.
I have been using this post How to select and change color of a button and revert to original when other button is clicked
as my reference and has helped me understand querySelectors and changing classes but for the life of me I cant see why my application isnt working.
Console.log('test)
fires right after the for loop is called but if put below the onClick
it does not fire.
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 am expecting to have 1/8 of the buttons to be yellow. That being the clicked button.
Rather than toggling the yellow and green classes - you can simply add a 'highlight' class on click and remove it from the previously clicked button.
This highlight class has the yellow background styling, so that when you click a button it adds the highlight class and yellow background. Then clicking another button removes the highlight class from the first button and applies it to the clicked one.
var buttons = document.querySelectorAll("button");
for (button in buttons) {
buttons[button].onclick = function() {
console.log('test')
buttons.forEach(function(btn){
btn.classList.remove('highlight');
})
this.classList.add('highlight');
}
}
button{
width: 100%;
padding: 10px 20px;
margin: 3px;
}
.green{
background-color: green;
}
.highlight {
background-color: yellow;
}
<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>