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();
}