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)