An easier way to write this line of code? Please?

Asked

Viewed 90 times

-2

I am developing a page that by pressing some keyboard keys, we trigger some sounds, like beats, claps and etc.

This line gives play in the audio when firing an event:

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

But I didn’t understand why it has a dollar sign, and I also wanted to know if there is any easier and/or clearer and didactic way. For example, you can get audio from the attribute data-key without it being ${e.keyCode}?

window.addEventListener('keydown',function (e) {
   const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);

   if (!audio) {
     return false;
   } else {
     audio.play();
   }
});
<div class="keys">
   <div data-key="65" class="key">
      <kbd>A</kbd>
      <span class="sound">clap</span>
   </div>
   <div data-key="83" class="key">
      <kbd>S</kbd>
      <span class="sound">hithat</span>
   </div>
   <div data-key="68" class="key">
      <kbd>D</kbd>
      <span class="sound">kick</span>
   </div>
   <div data-key="70" class="key">
      <kbd>F</kbd>
      <span class="sound">openhat</span>
   </div>
   <div data-key="71" class="key">
      <kbd>G</kbd>
      <span class="sound">boom</span>
   </div>
   <div data-key="72" class="key">
      <kbd>H</kbd>
      <span class="sound">ride</span>
   </div>
   <div data-key="74" class="key">
      <kbd>J</kbd>
      <span class="sound">snare</span>
   </div>
   <div data-key="75" class="key">
      <kbd>K</kbd>
      <span class="sound">tom</span>
   </div>
   <div data-key="76" class="key">
      <kbd>L</kbd>
      <span class="sound">tink</span>
   </div>
</div>

<audio data-key="65" src="sounds/clap.wav"></audio>
<audio data-key="83" src="sounds/hihat.wav"></audio>
<audio data-key="68" src="sounds/kick.wav"></audio>
<audio data-key="70" src="sounds/openhat.wav"></audio>
<audio data-key="71" src="sounds/boom.wav"></audio>
<audio data-key="72" src="sounds/ride.wav"></audio>
<audio data-key="74" src="sounds/snare.wav"></audio>
<audio data-key="75" src="sounds/tom.wav"></audio>
<audio data-key="76" src="sounds/tink.wav"></audio>

1 answer

4

There is! the String Concatenation that the binary operator is also used + (plus)

Example of String Concat:

const data = new Date();
// fazendo o uso do String Concat
document.write("<body>" + "<article>" + "<time datetime='" + data.toISOString() + "'>" + data + "</time>" + "</article>" + "</body>");

Example with Template Literals (or Template Strings):

const data = new Date();
// fazendo o uso do Template Strings
document.write(`<body><article><time datetime='${data.toISOString()}'>${data}</time></article></body>`);

and among other benefits of its use.


Noticeably there is also a difference in quantities of characters..

Making your code have a gain in line/character reduction. To others (in research), is also included a better performance gain in the results than normal concatenation in some cases!

Since the SE6, the addition of template literals allows us to INTERPOLATE strings

That is to say, Interpolate It is nothing more than mixing one or more expressions with Strings, in the following way becoming quite effective:

console.log(`É igual á ${2 + 2}`); // quanto é? com resultado

var calc = 2 + 2; // quanto é?
console.log("É igual á " + calc); // resultado

different from running the way above!


It is worth mentioning that the property KeyboardEvent.keyCode was deprecated! See some other alternatives like:

and among others..

Here is a small suggestion of clean code with the use of Template Strings!

// dispara o evento ao qualquer tecla ser pressionada
window.addEventListener('keydown', e => {
  // dar play na tag audio referente a tecla pressionada!
  document.querySelector(`audio[data-key=${e.key}]`).play();
});
<audio data-key="c" src="https://assets.mixkit.co/sfx/download/mixkit-one-clap-481.wav" />
<audio data-key="t" src="http://soundescapestudios.com/SESAudio/SES%20Site%20Sounds/PercussiveChimes/Crystal-02.wav" />

Run the snippet code and press the keys c or t to hear the sounds..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.