JavaScript Drum Kit

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

  1. We see that there is a bunch of styles provided in style.css.
  2. The html links to that css in the head tag.
  3. We can use querySelector with data-xyz data attribute to get the right audio element for the selected key!

We define the key as part of the div below:

1
2
3
4
<div data-key="65" class="key">
<kbd>A</kbd>
<span class="sound">clap</span>
</div>

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
2
3
4
5
6
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
if (audio) {
/* rewind the audio clip so we can play as soon as user hits key */
audio.currentTime = 0;
audio.play();
}

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! 🤗