Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0c1ac25

Browse files
committed
refactored code removed foreachs
1 parent f861b25 commit 0c1ac25

File tree

1 file changed

+15
-26
lines changed

1 file changed

+15
-26
lines changed

01 - JavaScript Drum Kit/index-START.html

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -59,38 +59,27 @@
5959

6060
<script>
6161

62-
const keys = document.querySelectorAll('.key')
63-
const audio = document.querySelectorAll('audio')
64-
62+
6563
const playSoundAndAnimateKey = (e) => {
66-
const keyname = e.key
67-
keys.forEach((key) => {
68-
if(key.children[0].textContent.toLowerCase() === keyname) {
69-
audio.forEach((sound) => {
70-
if(sound.dataset.key === key.dataset.key) {
71-
sound.currentTime = 0;
72-
sound.play()
73-
key.classList.toggle('playing')
74-
}
75-
})
76-
}
77-
})
64+
const key = document.querySelector(`div[data-key="${e.keyCode}"]`)
65+
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`)
66+
if(!audio) {
67+
return
68+
}
69+
audio.currentTime = 0;
70+
audio.play()
71+
key.classList.toggle('playing')
7872
}
7973

8074
const stopAnimationKey = (e) => {
81-
const keyname = e.key
82-
keys.forEach((key) => {
83-
if(key.children[0].textContent.toLowerCase() === keyname) {
84-
audio.forEach((sound) => {
85-
if(sound.dataset.key === key.dataset.key) {
86-
key.classList.toggle('playing')
87-
}
88-
})
89-
}
90-
})
75+
const key = document.querySelector(`div[data-key="${e.keyCode}"]`)
76+
if(!key) {
77+
return
78+
}
79+
key.classList.toggle('playing')
9180
}
9281

93-
document.addEventListener('keypress', playSoundAndAnimateKey, false)
82+
document.addEventListener('keydown', playSoundAndAnimateKey, false)
9483
document.addEventListener('keyup', stopAnimationKey, false)
9584

9685
</script>

0 commit comments

Comments
 (0)