I created a piano, and I have a case for each key. There are 61 of them.
I have a switch case for the keydowns, and for the keyups. So 122 cases !
I show you an exemple for 3 keys :
switch (e.key) {
// first row white keys
case '&':
document.getElementById("1").classList.add("active")
if (audio1.paused) {
audio1.play()
} else {
audio1.play()
audio1.currentTime = 0
}
break;
case 'é':
document.getElementById("2").classList.add("active")
if (audio2.paused) {
audio2.play()
} else {
audio2.play()
audio2.currentTime = 0
}
break;
case '"':
document.getElementById("3").classList.add("active")
if (audio3.paused) {
audio3.play()
} else {
audio3.play()
audio3.currentTime = 0
}
break;
Here is the link if you want : see the piano
Any idea how I can optimize this ?
You can create a hash map of the keys to the player ids, something like this:
const elems = {
'&': '1',
'é': '2',
'"': '3',
};
function toggleAudio(e) {
const id = elems[e.key];
const player = document.getElementById(id).classList.add('active');
if (!player.paused) player.currentTime = 0
player.play()
}