Skip to content

Commit 7b5caef

Browse files
committed
feat: add JS script
1 parent a73dc6d commit 7b5caef

3 files changed

Lines changed: 24 additions & 101 deletions

File tree

01 - JavaScript Drum Kit/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
GOAL: When a user opens this page and presses a key that corresponds with one of our div elements, we should play the audio clip associated with the keypress, add a class to the specific element that matches with the keypress and then remove that class in order to reset the element to it's original state.

01 - JavaScript Drum Kit/index-FINISHED.html

Lines changed: 0 additions & 84 deletions
This file was deleted.
Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<meta charset="UTF-8" />
55
<title>JS Drum Kit</title>
66
<link rel="stylesheet" href="style.css" />
7-
<link rel="icon" href="https://fav.farm/🔥" />
7+
<link rel="icon" href="https://fav.farm/" />
88
</head>
99
<body>
1010
<div class="keys">
@@ -57,27 +57,33 @@
5757
<audio data-key="76" src="sounds/tink.wav"></audio>
5858

5959
<script>
60-
document.addEventListener("keydown", (evt) => {
61-
const audio = document.querySelector(
62-
`audio[data-key="${evt.keyCode}"]`
63-
);
64-
const key = document.querySelector(`.key[data-key="${evt.keyCode}"]`);
65-
if (!audio) return;
66-
key.classList.add("playing");
60+
function removeTransition(e) {
61+
if (e.propertyName !== "transform") return;
62+
e.target.classList.remove("playing");
63+
}
64+
65+
function playSound(e) {
66+
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
67+
const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
68+
if (!audio) return; //stop the function from running when hitting a non available option
69+
70+
key.classList.add("playing"); //same as key.addClass in JQuery
71+
72+
/*Ensures that the sound always plays from the beginning. Otherwise,
73+
if the 'a' key is pressed twice rapidly, the soundclip will only play through
74+
once*/
6775
audio.currentTime = 0;
68-
audio.play();
69-
});
76+
audio.play(); // Play sound
77+
}
7078

71-
const keys = document.querySelectorAll(".key");
79+
const keys = Array.from(document.querySelectorAll(".key")); // Find all elements in the document with a class 'key'
80+
// Listen for any `keydown` events that occur on this browser window instance (this page)
81+
// When a `keydown` event is observered, trigger the `playSound` function, passing in the
82+
// `keydown` event as the argument (e)
83+
window.addEventListener("keydown", playSound);
7284
keys.forEach((key) =>
7385
key.addEventListener("transitionend", removeTransition)
7486
);
75-
76-
function removeTransition(evt) {
77-
if (evt.propertyName == "transform") {
78-
this.classList.remove("playing");
79-
} else return;
80-
}
8187
</script>
8288
</body>
8389
</html>

0 commit comments

Comments
 (0)