forked from caiovmessias/pianoInJs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
54 lines (40 loc) · 1.08 KB
/
main.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
54
const keys = document.querySelectorAll('.key');
window.addEventListener('load', start);
function playNote(event) {
let audioKeyCode = getKeyCode(event);
const key = document.querySelector(`.key[data-key="${audioKeyCode}"]`);
const cantFoundAnyKey = !key;
if (cantFoundAnyKey) {
return;
}
addPlayingClass(key);
playAudio(audioKeyCode);
}
function addPlayingClass(key) {
key.classList.add('playing');
}
function getKeyCode(event) {
let keyCode;
const isKeyBoard = event.type === 'keydown';
if (isKeyBoard) {
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 removePlayingClass(event) {
event.target.classList.remove('playing');
}
function start() {
keys.forEach(function (key) {
key.addEventListener('click', playNote);
key.addEventListener('transitionend', removePlayingClass);
});
window.addEventListener('keydown', playNote);
}