DEV Community

Cover image for JavaScript-30 Day-1
KUMAR HARSH
KUMAR HARSH

Posted on • Updated on

JavaScript-30 Day-1

Alt Text

I've completed my Day-1 challenge of #javascript30.

Today I made a Drum Kit using Vanilla JavaScript.

demo: https://lnkd.in/gKainBa

GitHub repo:

Lessons Learned:

  • Used attribute selector in JS for the first time and used the data-key property to pick the elements and to specify the exact Key Code of the pressed key we used the property name keyCode from the keypress event.
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`)
Enter fullscreen mode Exit fullscreen mode
  • Used 'data-' to create our own HTML attributes eg. data-key
<div data-key="65" class="key">
Enter fullscreen mode Exit fullscreen mode
  • we used audio.currentTime = 0 to prevent a delay when we play sound if we keep hitting a key repeatedly. What happens is .play() doesn't work on the audio files already playing so if we repeatedly press a key it won't affect the audio until it has finished playing after which if we press it will play again and to avoid this we set the current time of the audio to 0 (rewind it) every time the key is pressed so that the audio plays even if we spam the key (that is basically how I play drum lol).
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
audio.currentTime = 0;
audio.play();
Enter fullscreen mode Exit fullscreen mode

-To add some animation to the keys when pressed we add playing class to it when the event occurs but to remove that class we don't simply use setTimeout() as it can cause synchornization issues, rather we make use of transition end event and as soon as this event ends we remove the playing class , for this we use querySelectorAll as we have to explicity add the event listner to every single element in the Node List.

const keys = document.querySelectorAll(".key");
keys.forEach((key) => key.addEventListener("transitionend", removeTransition));
Enter fullscreen mode Exit fullscreen mode

-we also used <kbd> tag and I've never used it before.Read a blog post where the author said:

"The HTML Keyboard Input Element <kbd> represents user input and produces an inline element displayed in the browser's default monospace font."
I think I will need to do a bit more research on this one.

<div data-key="65" class="key">
kbd>A</kbd>
<span class="sound">clap</span>
</div>
Enter fullscreen mode Exit fullscreen mode

Useful Tip:
-We can find the Key Code of each key on the site keycode.info

Thank You!
Do comment if you find anything wrong or helpful.

You can follow me on:
Twitter
Linkedin

Top comments (4)

Collapse
 
rohitk570 profile image
ROHIT KUMAR

GREAT KEEP UP

Collapse
 
cenacr007_harsh profile image
KUMAR HARSH

Thanks.

Collapse
 
rash123 profile image
RASHMI VERMA

Best explain

Collapse
 
cenacr007_harsh profile image
KUMAR HARSH

Glad you liked it.