-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
56 lines (31 loc) · 1.21 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
55
56
const pianoKeys = document.querySelectorAll(".piano-keys .key"),
volumeSlider = document.querySelector(".volume-slider input"),
keysCheckbox = document.querySelector(".keys-checkbox input");
let allKeys = [],
audio = new Audio("tunes/a.wav"); //BY DEFAULT AUDIO SRC IS A TONE
const playTune = (key) => {
audio.src = `tunes/${key}.wav`; // PADDING AUDIO SRC BASED ON PASSED KEY
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);
// CALLING PLAYTUNE FUNCTION BY PASSING THE DATASET VALUE AS ARGUMENT
key.addEventListener("click", () => playTune(key.dataset.key))
});
const showHideKeys = () => {
pianoKeys.forEach(key => key.classList.toggle("hide"))
}
const handleVolume = (e) => {
audio.volume = e.target.value;
}
const pressedKey = (e) => {
if(allKeys.includes(e.key)) playTune(e.key);
}
keysCheckbox.addEventListener("click", showHideKeys);
volumeSlider.addEventListener("input", handleVolume);
document.addEventListener("keydown", pressedKey);