-
Notifications
You must be signed in to change notification settings - Fork 0
/
pianoscript.js
44 lines (36 loc) · 1.12 KB
/
pianoscript.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
const pianoKeys = document.querySelectorAll(".piano-keys .key"),
volumeSlider = document.querySelector(".volume-slider input"),
keysCheckbox = document.querySelector(".keys-checkbox input");
let allKeys = [],
audio = new Audio(`http://fahimbashar.com/staticfiles/tunes/a.wav`); //set default
const playTune = (key) =>
{
audio.src = `http://fahimbashar.com/staticfiles/tunes/${key}.wav`;
audio.play();
const clickedKey = document.querySelector(`[data-key="${key}"]`);
clickedKey.classList.add("active");
setTimeout(() =>
{
clickedKey.classList.remove("active");
}, 150);
}
pianoKeys.forEach(key =>
{
allKeys.push(key.dataset.key);
key.addEventListener("click", () => playTune(key.dataset.key));
});
const handleVolume = (e) =>
{
audio.volume = e.target.value;
}
const showHideKeys = () =>
{
pianoKeys.forEach(key => key.classList.toggle("hide"));
}
const pressedKey = (e) =>
{
if(allKeys.includes(e.key)) playTune(e.key);
}
keysCheckbox.addEventListener("click", showHideKeys);
volumeSlider.addEventListener("input", handleVolume);
document.addEventListener("keydown", pressedKey);