Home > database >  Unable to use .keyCode in query selector
Unable to use .keyCode in query selector

Time:01-10

I am tyring to use .keyCode in javascript to select a key that is pressed but each time a key is pressed the console prints null

Here's the related css code

  <audio data-key="65" src="sounds\crash.mp3"></audio>
  <audio data-key="83" src="sounds\kick-bass.mp3"></audio>
  <audio data-key="68" src="sounds\snare.mp3"></audio>
  <audio data-key="70" src="sounds\tom-1.mp3"></audio>
  <audio data-key="71" src="sounds\tom-2.mp3"></audio>
  <audio data-key="72" src="sounds\tom-3.mp3"></audio>
  <audio data-key="74" src="sounds\sound-effect-thriller-1-108404.mp3"></audio>
  <audio data-key="75" src="sounds\tom-4.mp3"></audio>
  <audio data-key="76" src="sounds\flautatravessera-46420.mp3"></audio>

Here's the javascript code that I have tried


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

It shows null at console.log(audio)

CodePudding user response:

Use backticks to delimit template literals.

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