0

Here variable "i" in soundsArray[i], not taking any values, line 4

   var soundsArray = ["crash", "kick-bass", "snare", "tom-1", "tom-2", "tom-3", "tom-4"];
    for(var i = 0; i<document.querySelectorAll(".drum").length; i++){
        document.querySelectorAll(".drum")[i].addEventListener("click", ()=>{
            var audio = new Audio(`./sounds/${soundsArray[i]}.mp3`);
            audio.play();
        });
    }  

   //document.querySelectorAll(".drum").length = 7
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
  • Could you explain what you mean by "not taking values"? – Hans Kesting Dec 05 '20 at 08:57
  • 1
    And what is the question? Show the HTML that defines the .drum-Class elelements. Say what you have done, what you expect to happen and what you observed instead. What is `Audio` the HTML5 dom element or from a library? – Peter Paul Kiefer Dec 05 '20 at 08:58

2 Answers2

0
for(var i = 0; i<soundsArray.length; i++){
    document.querySelectorAll(".drum")[i].addEventListener("click", ()=>{
        var audio = new Audio('./sounds/'+soundsArray[i]+'.mp3');
        audio.play();
    });
}  

I've modified it a bit, because I don't know if document.querySelectorAll(".drum")[i] will work properly for your code(will have to see html).

Try the above code, worked locally on my machine.

  • Got this from a different website,Because I used a var instead of a let. The reason is that a var is not block-scoped, which means that every audio would play the 8th sound (with index 7) of the array. And that doesn't exist. So use let in your for loop to get that fixed. – Paulson-G-Jose Dec 05 '20 at 09:56
  • Oh, It makes sense but i'll have to try it before confirming. – srinath-nanduri Dec 05 '20 at 13:13
0

a bit confusing!! however i prefer using somthing like this :

document.querySelectorAll(".drum").forEach((drm) =>{
    drm.addEventListener("click", (e)=>console.log(e.target.value))
})
<button class="drum" value="crash">crash</button>
<button class="drum" value="kick-bass">kick-bass</button>
<button class="drum" value="snare">snare</button>
<button class="drum" value="tom-1">tom-1</button>
<button class="drum" value="tom-2">tom-2</button>
<button class="drum" value="tom-3">tom-3</button>
<button class="drum" value="tom-4">tom-4</button>
b3hr4d
  • 4,012
  • 1
  • 11
  • 24