01 – JavaScript Drum Kit

JavaScript 30 is a pure JavaScript tutorial by WES BOS that will be implemented in 30 cases. This article is used to record the problems encountered in the process of DEMO production and thinking. This post was first published on my blog, Enjoy Reading!

demand

When the keyboard is pressed, the sound of the corresponding key is played and a simple effect is displayed on the button on the page.

Online DEMO source

steps

Step1: Listen for keyboard events

To make the page listen to the keyboard globally, use window.addeventListener (‘keydown’, function(){}).

Added: The difference between keyDown and KeyPress

  • keydownIt’s triggered by all the buttons, butkeypressIs triggered only by keys that generate character values. For example, arrow keys can triggerkeydown, but it cannot be triggeredkeypress.
  • keydownEvent KeyCode to indicate which key triggered the event, andkeypressThe supplied keycode will only say which character triggers the event. For example: when the keyboard is presseda.keyboardWill report65And thekeypressWill report97. It’s worth noting that,AIn any event will be reported as65.

Step2: Create a play function

  1. usingkeyCodedata-key[]Determine the audio and div elements for the buttons.
  2. Add the corresponding div elementplayingStyle.
  3. willaudioSet the playback time to 0, making sure the audio starts from the beginning before each playback.
  4. Play the audio.

Supplement 1: audio Other common attributes and methods

  1. attribute
    • Autoplay: Boolean attribute; Declare this property and the audio will automatically play as soon as possible without waiting for the entire audio file to download.
    • Controls: If this property is declared, the browser will provide a control panel that contains the sound, playback progress, and playback pause, allowing the user to control the playback of the audio.
    • Loop: Boolean attribute; If you declare this property, the audio is played in a loop.
  2. methods
    • Pause: Pauses the playback.

Supplement 2: classList

  • Instead of manipulating CSS with JS, for example:

    document.style.background="red";

    document.style.fontSize="24";

    Equivalent to [element style changed twice], which can cause backflow and redraw, reducing JavaScript performance.

  • You can use the list form if necessary, for example:

    document.getElementById("myDIV").classList.add("mystyle");

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

    key.classList.add('playing');
    audio.currentTime = 0;
    audio.play();
  }
Copy the code
.playing {
  transform: scale(1.1);
  border-color: #ffc600;
  box-shadow: 0 0 1rem #ffc600;
}
Copy the code

Step3: listen to the transitione end event

  1. Get all containsclassName=keyThe element.
  2. Fires when the element fires and finishes.
const key = Array.from(document.querySelectorAll('.key'));
key.forEach(key= > key.addEventListener('transitionend'.function(){}))
Copy the code

Supplement: ArrayForm

  • document.querySelectorAll()The element we get isNodeListAlthough,NodeListnotArray, but can still be usedforEachIterate, but older browsers are outdated and not implementedNodeList.forEach(). You can useArray.prototype.forEach()Array.form()To circumvent the problem.

Step4: Create the removeTransition function

  1. Determines the incoming eventpeopertyNameWhether it istransformIf not, exit.
  2. iftransform, then removeplayingStyle.
function removeTransition(e) {
  if(e.propertyName ! = ='transform') return;
  e.target.classList.remove('playing');
}
Copy the code

thinking

CSS typesetting syntax is used in the original example:

.keys {
    display: flex; /* To use flex, declare flex */ inside the element
    flex: 1; Flex: flex-grow | flex-shrink | flex-basis*/
    min-height: 100vh; /* vh = view height */
    align-items: center; /* Attributes that are valid only after being declared as flex, vertically centered */
    justify-content: center;/* A property that is valid only after it is declared flex, horizontally centered */
}
Copy the code

Refer to the

Document: keydown event – WebAPIs | MDN

<audio> – HTML | MDN

NodeList – Web APIs | MDN

Element.classList – Web APIs | MDN

flex – CSS: Cascading Style Sheets | MDN

JS30 record & result | Gua ‘s Note

JavaScript30 | a90100

At the end of the article, I would like to thank WES BOS and other domestic and foreign masters for open source their excellent works, making the threshold of learning lower. Enjoy Coding!