-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
56 lines (48 loc) · 1.47 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const drumpadButtons = document.querySelectorAll(".drum-pad");
const drumpadKeys = document.querySelectorAll(".clip");
const infoDisplay = document.querySelector("#display");
const drumpadButtonsArr = Array.from(drumpadButtons);
const drumpadKeysArr = Array.from(drumpadKeys);
// Stop target audio element and start it again.
function playAudio(clip) {
if (clip) {
clip.currentTime = 0;
clip.pause();
clip.play();
}
}
// Use audio element ID to create display description
function renderDescription(id) {
infoDisplay.innerText = id
.split("-")
.map((word) => word[0].toUpperCase() + word.slice(1))
.join(" ");
}
// Add animation to drumheads on click or keypress
function animateDrumhead(target) {
target.classList.add("active-drumhead");
target.onanimationend = () => target.classList.remove("active-drumhead");
}
// Using audio container div, play audio and render changes to DOM
function activateDrumhead(target) {
const audio = target.querySelector("audio");
playAudio(audio);
renderDescription(target.id);
animateDrumhead(target);
}
function handleDrumpadEvent(event) {
activateDrumhead(event.target);
}
function handleKeyPress(event) {
const clip = drumpadKeysArr.find(
(item) => item.id === event.key.toUpperCase()
);
if (clip) {
activateDrumhead(clip.parentElement);
}
}
// Add event listener to each drumpad button
for (element of drumpadButtonsArr) {
element.addEventListener("click", handleDrumpadEvent);
}
window.addEventListener("keydown", handleKeyPress);