I've been struggling with a specific issue in my 9-button grid. When I click on a button and it changes color to orange, if I click on another button, both buttons remain orange. What I want is for only one button at a time to be orange - when a new button is clicked, the previous one should return to its normal color. My limited knowledge of JavaScript and HTML has made it challenging to pinpoint where the problem lies.
function switchColor() {
var currentButton = this;
var allButtons = document.querySelectorAll('.btn');
allButtons.forEach(button => {
if (button !== currentButton) {
button.classList.remove('btn2');
button.classList.add('btn');
}
});
if (currentButton.classList.contains('btn')) {
currentButton.classList.remove('btn');
currentButton.classList.add('btn2');
} else {
currentButton.classList.remove('btn2');
currentButton.classList.add('btn');
}
}
document.getElementById('sel').addEventListener('click', switchColor);
/* Your CSS styles here */
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8>";
<link rel="stylesheet" href="Normalize.css">
<link rel="stylesheet" href="Style.css">
<title>Document</title>
</head>
<body>
<!-- Your HTML content here -->
</body>
</html>
To address the issue, I have created a JavaScript function called `switchColor()` that removes the colored state from all buttons except the one currently being clicked. The `eventListener` is added specifically to the 'sel' button to trigger this behavior. As you can see, there are some inconsistencies in the way variables are declared, but this is how I have found similar functions implemented online. Please let me know if you need further clarification or assistance.