1

I have a folder of 7 sounds. I am trying to assign a different sound to be played when each of seven buttons is clicked.

However, instead all buttons are getting assigned the last sound in my folder. Why is this happening?

var soundFiles = ["crash", "kick-bass", "snare", "tom-1",
                  "tom-2", "tom-3", "tom-4"];


for (var i = 0; i < document.querySelectorAll("button").length; i++) {
  var filename = "sounds/" + soundFiles[i] + ".mp3";
  console.log(filename); // prints each filename
  document.querySelectorAll("button")[i].addEventListener("click", function() {
    playSound(filename)
  });

}

  function playSound(file) {
    console.log("file = " + file); // only prints the last filename: "sounds/tom-4.mp3"
    var audio = new Audio(file);
    audio.play();
  }
Katherine
  • 207
  • 1
  • 3
  • 11
  • 1
    I just learned how to fix this issue by using `bind`. Inside my for loop I now have the line `document.querySelectorAll(".drum")[i].addEventListener("click", playSound.bind(null, filename));` and the issue is resolved. – Katherine Sep 24 '20 at 17:04
  • [It is perfectly valid to answer your own question](https://stackoverflow.com/help/self-answer) – Boaz Sep 24 '20 at 17:15
  • Though in this case, the question is apparently a duplicate. – Boaz Sep 24 '20 at 17:20
  • Thank you Boaz! You're right... because this question has been marked a duplicate, I don't have the option to answer. I will keep this in mind for next time. – Katherine Sep 25 '20 at 17:25

0 Answers0