-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
53 lines (41 loc) · 1.13 KB
/
script.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const keys = document.getElementsByClassName('key');
function playNote(event) {
let audioKeyCode = getKeyCode(event);
const key = document.querySelector(`.key[data-key="${audioKeyCode}"]`)
if(key == null) {
return;
}
addPlayingClass(key);
playAudio(audioKeyCode);
}
function addPlayingClass(key) {
key.classList.add('playing')
}
function removePlayingClass(event) {
event.target.classList.remove('playing')
}
function getKeyCode(event) {
let keyCode;
const keyboardPressed = event.type === 'keydown'
if(keyboardPressed) {
keyCode = event.keyCode
} else {
keyCode = event.target.dataset.key
}
return keyCode
}
function playAudio(audioKeyCode) {
const audio = document.querySelector(`audio[data-key="${audioKeyCode}"]`)
audio.currentTime = 0;
audio.play()
}
function eventRegister() {
//mouse
for(key of keys) {
key.addEventListener('click', playNote)
key.addEventListener('transitionend', removePlayingClass)
}
//keyboard
window.addEventListener('keydown', playNote)
}
window.addEventListener("load", eventRegister)