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}"]`)
- Used 'data-' to create our own HTML attributes eg.
data-key
<div data-key="65" class="key">
- 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();
-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));
-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>
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.
Top comments (4)
GREAT KEEP UP
Thanks.
Best explain
Glad you liked it.