forked from wesbos/JavaScript30
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
33 lines (22 loc) · 821 Bytes
/
index.js
File metadata and controls
33 lines (22 loc) · 821 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const playDrum = (whichDrum) => {
const audio = document.querySelector(`audio[data-key="${whichDrum}"]`)
const key = document.querySelector(`.key[data-key="${whichDrum}"]`)
if (!audio) return
key.classList.add('playing')
audio.currentTime = 0 // reset to beginning of the sound
audio.play()
}
function stopPlaying(event) {
if (event.propertyName !== 'transform') return
event.target.classList.remove('playing')
}
window.addEventListener('keydown', (event) => playDrum(event.keyCode))
const keys = document.querySelectorAll('.key')
keys.forEach(key => {
key.addEventListener('click', (event) => {
const clicked = event.path.filter((node) => node.className === 'key')
if (!clicked) return
playDrum(clicked[0].dataset.key)
})
key.addEventListener('transitionend', stopPlaying)
})