Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate through multiple elements of querySelectorAll with forEach

Problem is as following: I have created a separate JS file, in which I want to iterate through elements belonging to a certain class audioz. In the second line of my JS code I use the addEventListener on item, however the code does not seem to work with item, only if I put document, but the result remains flawed. What am I doing wrong in the iteration?

JS Code:

document.querySelectorAll('.audioz').forEach(item => {
    item.addEventListener('keydown', function(e) {
    const ss = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    console.log(ss);
    ss.play();
})})

HTML:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  <audio class="audioz" data-key="65" src="sounds/clap.wav"></audio>
  <audio class="audioz" data-key="83" src="sounds/hihat.wav"></audio>
  <audio class="audioz" data-key="68" src="sounds/kick.wav"></audio>
  <audio class="audioz" data-key="70" src="sounds/openhat.wav"></audio>
  <audio class="audioz" data-key="71" src="sounds/boom.wav"></audio>
  <audio class="audioz" data-key="72" src="sounds/ride.wav"></audio>
  <audio class="audioz" data-key="74" src="sounds/snare.wav"></audio>
  <audio class="audioz" data-key="75" src="sounds/tom.wav"></audio>
  <audio class="audioz" data-key="76" src="sounds/tink.wav"></audio>

>Solution :

You are currently adding a keydown event listener to each audio tag. However, the audio tag is hidden, so you can’t execute the keydown event on it. Thus, your code will not work.

Add the event listener to the document instead.

document.addEventListener('keydown', function(e) {
  const ss = document.querySelector(`audio[data-key="${e.keyCode}"]`);
  console.log(ss);
  ss.play();
})
<audio class="audioz" data-key="65" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio> press the A key
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading