-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (47 loc) · 1.4 KB
/
index.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
57
58
59
60
61
62
63
import { keys } from "./keys.js";
const keysContainer = document.querySelector(".keys");
keys.forEach((key) => {
const keyElement = document.createElement("div");
const kbdElement = document.createElement("kbd");
const spanElement = document.createElement("span");
keyElement.classList.add("key");
kbdElement.textContent = key.key;
spanElement.classList.add("sound");
spanElement.textContent = key.sound;
keyElement.appendChild(kbdElement);
keyElement.appendChild(spanElement);
const sound = new Audio(`./sounds/${key.sound}.wav`);
keyElement.addEventListener("click", () => {
sound.currentTime = 0;
sound.play();
keyElement.classList.add("playing");
});
keyElement.addEventListener("transitionend", () => {
keyElement.classList.remove("playing");
});
keysContainer.appendChild(keyElement);
});
window.addEventListener("keydown", playSound);
function playSound(event) {
const sounds = {
A: "clap",
S: "hihat",
D: "kick",
F: "openhat",
G: "boom",
H: "ride",
J: "snare",
K: "tom",
L: "tink",
}[event.key.toUpperCase()];
const sound = new Audio(`./sounds/${sounds}.wav`);
const keys = document.querySelectorAll(".key");
if (!sound) return;
sound.currentTime = 0;
sound.play();
keys.forEach((key) => {
if (key.children[0].textContent === event.key.toUpperCase()) {
key.classList.add("playing");
}
});
}