Drum Kit with Vanilla JavaScript

·

2 min read

Before going into the application, I want to explain a few things so that beginners will get a clear idea at the code level.

Vanilla-JS is used to refer to pure JavaScript without using any extra libraries.

“Window” Object represents a window in the browser. It is automatically created by the browser and not part of the JavaScript objects.

“addEventListener()” is used for attaching an event handler to a specific element and it is an in-built function of JavaScript. We can add multiple event handlers to a specific element without overwriting the existing event handlers.

“querySelector()” method returns the first element that matches the CSS selector.

Example: HTML Code

<p>This is a sample</p>

JavaScript Code

<script>
document.querySelector(”p”)
</script>

The “data-*” attribute is used to store custom data that is private to the page or application and it allows us to embed custom data to the HTML elements so that the stored data can be used in javascript to create an efficient user experience. it shouldn’t contain any uppercase letter and “data-” should be a prefix. the value can be any string.

syntax -

<div data-heading-type=”h1”>Hello World..!</div>

To start creating the Drum Kit application with JavaScript, Please download the starter files and template from this repo - https://github.com/suryatejaj97/vanilla-javascript/tree/main/0 - Drum Kit/starter-template

In this application, we are going to create a drum kit application that plays varieties of sounds while pressing the keys on your keyboard.

In our traditional keyboards which we are using in laptops (or) PC by default, there is a unique code assigned to each key. Refer to the link below to get a clear idea of the unique code in the keyboard. https://www.toptal.com/developers/keycode

Now we will be using the tag with the attribute of “data-key”. Make sure to download the starter template from the GitHub repo and add the following functions in the <script> tag.

<script>
    function removeTransition(e) {
      if (e.propertyName !== 'transform') return;
      e.target.classList.remove('playing');
    }

    function playSound(e) {
      const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
      const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
      if (!audio) return;

      key.classList.add('playing');
      audio.currentTime = 0;
      audio.play();
    }

    const keys = document.querySelectorAll('.key')

    keys.forEach(key => key.addEventListener('transitionend', removeTransition))
    window.addEventListener('keydown', playSound);
</script>

And the output will be shown below, Screenshot (3).png

You can download the entire codebase which includes CSS and required audio files from this repo - https://github.com/suryatejaj97/vanilla-javascript/tree/main/0 - Drum Kit