0

Just started using data attributes in HTML and I was trying to select an audio element based on a certain key. (FYI, these keys map to the keys on home row.)

To clarify, the trouble has nothing to do with audio or getting it to play.

What I'm finding is that with this code there are differences in behavior depending on whether I'm using

`

or

'

Depending on which one I use, there are differences in output to the console. Code below:

<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>
<script>
window.addEventListener('keydown', function(e) {
var audio = document.querySelector(`audio[data-key="${e.keyCode}"]`); //Works
    audio = document.querySelector('audio[data-key="${e.keyCode}"]'); //Doesnt Work
console.log(audio);
});
</script>

When I remove the second assignment statement the console shows me that is has selected the element. When I hit 'a' the console shows:

<audio data-key="65" src="sounds/clap.wav"></audio>

However, when I leave in the second assignment statement or use that to declare audio, the console shows "null" for whatever key is pressed.

Why is this happening? Why would JavaScript prefer ` to '? (More info: I'm using a Mac with Google Chrome's inspect to look at the console, and I'm editing with SublimeText)

Gelok
  • 174
  • 3
  • 10
  • 2
    Back-quotes allow expressions to be evaluated (`${e.keyCode}`) inside the string. Single- and double-quote strings don't do that. The back-quote syntax is fairly new. – Pointy Jun 21 '17 at 18:36
  • The first one is a template string, the second is a plain old strong. – ste2425 Jun 21 '17 at 18:37
  • https://stackoverflow.com/questions/27678052/what-is-the-usage-of-the-backtick-symbol-in-javascript and https://stackoverflow.com/questions/42753169/use-of-apostrophe-vs-single-quote-backtick – j08691 Jun 21 '17 at 18:37
  • 1
    See this MDN page for [more info on Template Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), which use the grave accent. – Lynn Crumbling Jun 21 '17 at 18:38
  • 2
    You can often save yourself some time when you've got a question like this by doing a Google search for something like "MDN JavaScript string syntax". The Mozilla site ("MDN") has lots of documentation about web technologies. – Pointy Jun 21 '17 at 18:39
  • By the way in a world which includes IE doesn't support the ` syntax – apokryfos Jun 21 '17 at 18:41

0 Answers0