When adding event listener to a batch of objects in Javascript, can I use a for loop instead switch statement to specify different scenarios?

14

So basically I am trying to play different sound files for different buttons when clicked. I wrote a switch statement and it worked. I tried to simplify the code and write a for loop instead. However, the for loop doesn't work. Is it bcs there is the i variable in for loop's scenarios?

for loop

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

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

switch statement

for (var i = 0; i < document.querySelectorAll(".drum").length; i++) {
  document.querySelectorAll(".drum")[i].addEventListener("click", function() {
    switch (this.innerHTML) {
      case "w":
        var crash = new Audio("sounds/crash.mp3");
        crash.play();
        break;
      case "a":
        var kick = new Audio("sounds/kick-bass.mp3");
        kick.play();
        break;
      case "s":
        var snare = new Audio("sounds/snare.mp3");
        snare.play();
        break;
      case "d":
        var tom1 = new Audio("sounds/tom-1.mp3");
        tom1.play();
        break;
      case "j":
        var tom2 = new Audio("sounds/tom-2.mp3");
        tom2.play();
        break;
      case "k":
        var tom3 = new Audio("sounds/tom-3.mp3");
        tom3.play();
        break;
      case "l":
        var tom4 = new Audio("sounds/tom-4.mp3");
        tom4.play();
        break;
      default:
        console.log(this.innerHTML)

    }
    var soundSrc = "sounds/" + soundFiles[i];
    var audio = new Audio(soundSrc);
    audio.play();
  });
}

answered question

You could set up all the audio on page load and then only play when needed?

1 Answer

10

First, call .querySelectorAll() once:

let drums = document.querySelectorAll(".drum");

Then in your loop, use let instead of var:

for (let i = 0; i < drums.length; i++) {
  drums[i].addEventListener("click", function() {
    var soundSrc = "sounds/" + soundFiles[i];
    var audio = new Audio(soundSrc);
    audio.play();
  });
}

posted this

Have an answer?

JD

Please login first before posting an answer.