DEV Community

Emmanuel
Emmanuel

Posted on

javascript30 journey - day 1

The first lesson on Javascript30 is building a drum kit (I built mine check it out) its a really fun project, here's a summary of how it works.

First we need to created nine(9) divs to represent all the sounds present.

browser view

The sounds are all different, each div represents a sound, to actually play the sound we need to create 9 audio elements.
Normally the audio element won't appear in the browser if you add just the 'src' attribute without any other thing. you should still declare 'display: none' in the CSS file regardless.

One important thing in the div elements is the addition of custom attribute using the 'data-' attribute . In this project we added the KeyboardEvent.code value of every letter as an attribute to it.
For example : 'data-key = keyA' and also to it corresponding sound in the audio element. This will be useful in the Javascript code.

HTML Code

After creating the all HTML elements and styling with CSS, the major task is the functionality:

javascript code

for the Javascript code, three(3) main functions are needed:

  1. The first function is the playsound function.
  2. The second is the addTransition function.
  3. Then the removeTransition function.

The playSound function will be a callback function in the keydown event listener.
it plays the sound of the audio element containing the same attribute as the element of the key clicked .
it also calls the addTransition function.
An important part of the code is "audio.currentTime = 0" line.
Its make sure the audio element plays the sound every single time the playSound function is called(it stops any current sound that was previously played)

The addTransition function adds the class "playing" to any div that was clicked to give it that nice quick bouncy transition.

The removeTransition function as the name states removes the transition on any clicked element by removing the class "playing". Its passed as a callback function to the "transitionend" event listener.

After creating all three(3) functions we'll create the keydown event which calls the playsound function .
Then we get all the divs representing different sounds and pass the transitionend event which calls the remove transition function to each of them using the forEach method.

that's all guys, you've successfully created a drumkit.
super grateful to wesbos for creating such an amazing resource.
visit javascript30 to join me in sharpening your javascript skills.

✌️

Top comments (0)