I'm making virtual keyboard which accepts sound and a background color when a specific key at the keyboard is pressed. So far so good, I implement the sound and the visual CSS background effect at each key, but only the letter keys, special keys accept only sound without the background color which is CSS class .is-pressed.
Little example: I catch the letter keys with different classed which are equal to the EventListener who listens for specific key pressed.
<div class="keyboard__row">
<kbd class="keyboard__key keyboard__key--size2">Tab</kbd>
<kbd class="q keyboard__key">Q</kbd>
<kbd class="w keyboard__key">W</kbd>
<kbd class="e keyboard__key">E</kbd>
<kbd class="r keyboard__key">R</kbd>
<kbd class="t keyboard__key">T</kbd>
<kbd class="y keyboard__key">Y</kbd>
<kbd class="u keyboard__key">U</kbd>
<kbd class="i keyboard__key">I</kbd>
<kbd class="o keyboard__key">O</kbd>
<kbd class="p keyboard__key">P</kbd>
<kbd class=" keyboard__key">{</kbd>
<kbd class=" keyboard__key">}</kbd>
<kbd class="keyboard__key keyboard__key--size3">\</kbd>
/**
* Function that listen for pressed keys and creating visual
* effect at the current pressed key.
*/
document.addEventListener("keypress", function(event) {
keySound(event.key);
keyAnimation(event.key);
});
/**
* Adding the audio file to the specific pressed key.
*/
function keySound(key) {
let audio = new Audio("assets/sounds/key-sound.mp3");
audio.play();
}
/**
* Selecting by class name of each key, and do background effect with timeout.
*/
function keyAnimation(currentKey) {
let activeKey = document.querySelector("." + currentKey);
activeKey.classList.add("is-pressed");
setTimeout(function () {
activeKey.classList.remove("is-pressed");
}, 100);
}