-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
49 lines (46 loc) · 1.32 KB
/
Copy pathscript.js
File metadata and controls
49 lines (46 loc) · 1.32 KB
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
let justPlayed = null;
const playSound = (key) => {
if (key === justPlayed) return;
const keyElement = document.querySelector(`div[data-key="${key}"]`);
let audio = document.querySelector(`audio[data-key="${key}"]`);
if (keyElement != null) {
keyElement.classList.add("playing");
audio.addEventListener("ended", () => {
keyElement.classList.remove("playing");
});
} else {
audio = document.querySelector(`audio[data-key="other"]`);
}
audio.currentTime = 0;
audio.play();
justPlayed = key;
};
function removeTransition(e) {
if (e.propertyName !== "transform") return;
e.target.classList.remove("playing");
}
window.addEventListener("keydown", (e) => {
playSound(e.key);
});
window.addEventListener("keyup", () => {
justPlayed = null;
});
const keys = Array.from(document.querySelectorAll(".key"));
keys.forEach((key) => key.addEventListener("transitionend", removeTransition));
window.addEventListener("click", (e) => {
if (
e.target.parentNode.classList[0] != "key" &&
e.target.parentNode.classList[0] != "keys"
) {
playSound(null);
} else {
keys.forEach((key) => {
key.addEventListener("pointerdown", (e) => {
playSound(e.currentTarget.dataset.key);
});
key.addEventListener("pointerup", (e) => {
justPlayed = null;
});
});
}
});