Skip to content

Commit bdbec7c

Browse files
committed
Day-1
1 parent 41ad4cb commit bdbec7c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

01 - JavaScript Drum Kit/index-START.html

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,37 @@
5858
<audio data-key="76" src="sounds/tink.wav"></audio>
5959

6060
<script>
61+
const findSound = key => document.querySelector(`audio[data-key="${key}"]`);
62+
const findButton = key => document.querySelector(`.keys [data-key="${key}"]`);
63+
const findKeyRoot = leaf => leaf.closest(`[data-key]`);
64+
const keyContainer = document.querySelector(".keys");
6165

66+
const playSound = (audio, onStart, onStop) => {
67+
audio.onplaying = onStart;
68+
audio.onended = onStop;
69+
audio.play();
70+
};
71+
72+
const handlePlaying = (el, sound) => {
73+
const onPlaying = () => el.classList.add("playing");
74+
const onEnded = () => el.classList.remove("playing");
75+
playSound(sound, onPlaying, onEnded);
76+
};
77+
78+
document.addEventListener("keydown", ({ keyCode }) => {
79+
const el = findButton(keyCode);
80+
if (!el) return;
81+
const sound = findSound(keyCode);
82+
handlePlaying(el, sound);
83+
});
84+
85+
keyContainer.addEventListener("click", ({ target }) => {
86+
const el = findKeyRoot(target);
87+
if (!el) return;
88+
const key = el.dataset.key;
89+
const sound = findSound(key);
90+
handlePlaying(el, sound);
91+
});
6292
</script>
6393

6494

0 commit comments

Comments
 (0)