Preface
I’m investing a major portion of this month working on the JavaScript30 course by Wes Bos. The course is free and the content looks quite promising. It uses vanilla JS, so it looks like a decent way to build some JS chops without getting bogged down in JS framework hell. Here goes 🤞…
Day 1: JavaScript Drum Kit
In this section we build a fun little drumkit. The exercise files are here.
Step 1: Understand the CSS and HTML provided
- We see that there is a bunch of styles provided in style.css.
- The html links to that css in the head tag.
- We can use
querySelector
withdata-xyz
data attribute to get the right audio element for the selected key!
We define the key as part of the div
below:
1 | <div data-key="65" class="key"> |
And there is a corresponding audio element on the page as follows:
1 | <audio data-key="65" src="sounds/clap.wav"></audio> |
Very Cool! 😎
Step 2: Hooking up the audio to the key event
To allow a key event to generate the correct audio we use a query selector in our event listener as follows:
1 | const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`); |
The rewinding is important so that our clip plays as soon as key is hit.
Step 3: Animation
We want to apply a highlight to the key being played. This can be done by temporarily adding a new style and then removing it.
To do this, we need to get the element on which we need to apply the style using a query selector again. And we apply the playing
class to it while it is playing.
See list of CSS selectors here.
However, we also need to be able to disable it once it has finished.
It turns out that there is a way to determine when a transition has stopped. We can use this as the trigger.
Working demo is here.
Code is here.
That’s all folks! 🤗