-1

So I am not able to make this code work. What should happen is, an audio file should play whenever I press a key that is corresponding to the audio. But for some reason whenever I press the key, nothing happens. Please help?

window.addEventListener("keydown", function (ev)
{
    const audio = document.querySelector("audio[data-key='${ev.keyCode}']");
    if (!audio) return;
    audio.play();
});
<body>
<div class="container">
    <div data-key="65" class="key">
        <kbd>A</kbd>
        <span>CLAP</span>
    </div
    ><div data-key="83" class="key">
    <kbd>S</kbd>
    <span>HIHAT</span>
</div
><div data-key="68" class="key">
    <kbd>D</kbd>
    <span>KICK</span>
</div
><div data-key="70" class="key">
    <kbd>F</kbd>
    <span>OPENHAT</span>
</div
><div data-key="71" class="key">
    <kbd>G</kbd>
    <span>BOOM</span>
</div
><div data-key="72" class="key">
    <kbd>H</kbd>
    <span>RIDE</span>
</div
><div data-key="74" class="key">
    <kbd>J</kbd>
    <span>SNARE</span>
</div
><div data-key="75" class="key">
    <kbd>K</kbd>
    <span>TOM</span>
</div
><div data-key="76" class="key">
    <kbd>L</kbd>
    <span>TINK</span>
</div>
    <audio data-key="65" src="audio/clap.wav"></audio>
    <audio data-key="83" src="audio/hihat.wav"></audio>
    <audio data-key="68" src="audio/kick.wav"></audio>
    <audio data-key="70" src="audio/openhat.wav"></audio>
    <audio data-key="71" src="audio/boom.wav"></audio>
    <audio data-key="72" src="audio/ride.wav"></audio>
    <audio data-key="74" src="audio/snare.wav"></audio>
    <audio data-key="75" src="audio/tom.wav"></audio>
    <audio data-key="76" src="audio/tink.wav"></audio>
</div>

<!-- Main Script -->
<script src="js/script.js"></script>
</body>

My approach might be totally wrong, if that's the case what do I need to do to in order to make it work ?

Martin Zahariev
  • 697
  • 1
  • 7
  • 6

1 Answers1

0

Your problem is your query selector:

const audio = document.querySelector("audio[data-key='${ev.keyCode}']")

You're trying to use the variable substitution, but that only works when using backticks (``), not double-quotation marks (""). In double-quotation marks, it'll just be treated as normal text (i.e., it equals audio[data-key='${ev.keyCode}']).

Switch to backticks and it should be just fine:

const audio = document.querySelector(`audio[data-key='${ev.keyCode}']`)

This will resolve to something like: audio[data-key='65']

samanime
  • 25,408
  • 15
  • 90
  • 139