-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
39 lines (31 loc) · 1.19 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
// --------------------------------- \\
// -------- JavaScript Page -------- \\
// --------------------------------- \\
const keys = document.querySelectorAll('.key');
const regulars = document.querySelectorAll('.key.white');
const sharps = document.querySelectorAll('.key.black');
const whitekey = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';'];
const blackkey = ['w', 'e', 't', 'y', 'u', 'o', 'p'];
// -- play via mobile and/or mouse click -- //
keys.forEach(key => {
key.addEventListener('click', () => playNote(key))
});
// -- play via desktop keyboard -- //
document.addEventListener('keydown', e => {
if (e.repeat) return;
const key = e.key;
const whiteKeyIndex = whitekey.indexOf(key);
const blackKeyIndex = blackkey.indexOf(key);
if (whiteKeyIndex > -1) playNote(regulars[whiteKeyIndex]);
if (blackKeyIndex > -1) playNote(sharps[blackKeyIndex]);
});
// -- click to play audio function -- //
let playNote = (key) => {
const noteSound = document.getElementById(key.dataset.note);
noteSound.currentTime = 0;
noteSound.play();
key.classList.add('active');
noteSound.addEventListener('ended', () => {
key.classList.remove('active')
});
};