I am expecting the code to generate values of string as “sounds/tom-1.mp3”,”sounds/tom-2.mp3″… etc. and play that audio. But the code is generating value of string as “sounds/tom-8.mp3” each time the button is clicked.
I tried commenting out the addEventListener and looked at the values of i inside and outside function fn and the code worked just fine. Problem arises only when value of i is 8
var num_of_btn = document.querySelectorAll(“.drum”).length;
code:
for(var i=0;i<num_of_btn;i++){
var btn = document.querySelectorAll(".drum")[i];
btn.addEventListener("click",fn);
function fn(){
alert("This is inside the function" + (i+1).toString());
var string = "sounds/tom-"+(i+1).toString() + ".mp3";
alert(string);
var audio = new Audio(string);
audio.play();
}
}