I have developed a website featuring multiple buttons that can be clicked using the mouse or activated with corresponding keyboard letters. When a user presses the assigned letter on the keyboard, the button should play a unique sound and change its text color to orange. Everything is functioning correctly except for one issue - when a button is activated via keyboard input, the text color does not change on-screen. Can you help me identify what's causing this problem in my code?
Below is the JavaScript code snippet used in my project:
// Button click detection
for (var i = 0; i <= 6; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
var buttonInnerHTML = this.innerHTML;
this.style.color = "orange";
makeSound(buttonInnerHTML);
}
);
}
// Keyboard keydown detection works but doesn't change color
document.addEventListener("keydown", function(event) {
var button = event.target;
var buttonInnerHTML = button.innerHTML;
button.style.color = "orange";
makeSound(event.key);
})
// Sound generation function
function makeSound(key) {
switch (key) {
case "w":
var tom1 = new Audio("sounds/tom-1.mp3");
tom1.play();
break;
// Additional cases for other keys...
default:
console.log(buttonInnerHTML);
}
}
And here is a snippet of the HTML body related to these buttons:
<body>
<h1 id="title">Drum 🥁 Kit</h1>
<div class="set">
<button class="w drum">w</button>
<button class="a drum">a</button>
<button class="s drum">s</button>
<button class="d drum">d</button>
<button class="j drum">j</button>
<button class="k drum">k</button>
<button class="l drum">l</button>
</div>
<script src="index2.js" charset="utf-8"></script>
<footer>
</footer>
</body>