0

This simple code should return an audio file in the console when pressed "a" but it is giving me NULL

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Drum Kit</title>
<link rel="stylesheet" href="style.css">
</head>
<body>


<div class="keys">
<div data-key="65" class="key">
  <kbd>A</kbd>
  <span class="sound">clap</span>
</div>

<audio data-key="65" src="./sounds/clap.wav"></audio>
<script>
window.addEventListener('keydown', function(e){
 const audio = document.querySelector('audio[data-key="${e.keyCode}"]');
 console.log(audio);              
  });
</script>


</body>
</html>

This not a duplicate question, this question had problem of using template literal, other all question were regarding misplacing script tag.

Ahmed Raza
  • 11
  • 1
  • 3
  • 1
    Because `audio[data-key="${e.keyCode}"]` does not what you expect it to do – Andreas Dec 03 '17 at 12:10
  • You either want `const audio = document.querySelector('audio[data-key="' + e.keyCode + '"]');` or (ES2015+) `const audio = document.querySelector(\`audio[data-key="${e.keyCode}"]\`);` – T.J. Crowder Dec 03 '17 at 12:11
  • 1
    That's just a normal string, inside of it `${e.keyCode}` just just literally "${e.keyCode}", I think you meant to use a [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)? – Useless Code Dec 03 '17 at 12:13
  • @T.J.Crowder Your comment solved the problem, "const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);". I actually meant this, I still don't know how to put " ` ", even didn't know this exist, Thanks for your answer, other all answers were referring to put the code at the bottom or some thing like that which it already is. Thanks for your answer – Ahmed Raza Dec 03 '17 at 12:22
  • @T.J.Crowder I have read documentation about back ticks, and this was the mistake my code had, I even had to google how to type back tick and I am not ashamed of it, I am here to learn, and now I know template literal thanks to you... – Ahmed Raza Dec 03 '17 at 12:33
  • @AhmedRaza: Glad that helped. :-) Just beware that if you have to support older browsers, they won't have template literal support (IE11, for instance). Happy coding! – T.J. Crowder Dec 03 '17 at 12:34

0 Answers0