<section id="color-palette">
<button >Black</button>
<button >Generate</button>
<button >Generate</button>
<button >Generate</button>
</section>
function selectedColor(){
buttonOne.classList.toggle('selected');
}
buttonOne.addEventListener('click', selectedColor);
CodePudding user response:
Question 1
If you simply want to toggle each button:
const buttons = Object.values(document.getElementsByClassName("color"));
function selectedColor(e) {
e.target.classList.toggle("selected");
console.log(e.target.classList)
}
buttons.forEach(function(button) {
button.addEventListener("click", selectedColor);
});
Question 2
Per your second question, if you want to allow only one button at a time to have the active class toggled on:
const buttons = Object.values(document.getElementsByClassName("color"));
function selectedColor(e) {
buttons.forEach(function (button) {
button === e.target
? button.classList.toggle("selected")
: button.classList.remove("selected");
console.log(button.classList);
});
}
buttons.forEach(function(button) {
button.addEventListener("click", selectedColor);
});