Search code examples
javascripthtmlaudioonclicksrc

use for-loop in javascript to assign different sources for audiofiles


I'm trying to build a soundboard (similar to therapboard dot com) - and i want javascript to create the images (named niels1.png, niels2.png...) alongside the fitting sound (1.ogg, 2.ogg,...) when the image is clicked, via a loop.

The image part works, there's also a sound being played when i click on any of the images, but it's the same sound (in this case the last from the loop... so 3.ogg). Is what i want doable with the fairly easy start i've come up with so far?

    <script>
var i;
for(i=0; i<4; i++){
    var imgsrc = "niels" + i + ".png";
    var audiosrc = i + ".ogg";
    var image = document.createElement("IMG");
    image.setAttribute("src", imgsrc);
    image.addEventListener('click', myPlay);

    var audio = document.createElement('audio');
    audio.src = audiosrc;

    function myPlay(){
        var audio = new Audio (audiosrc);
        audio.play();
    }

    document.body.appendChild(image);

}
</script>

Solution

  • Try this. You have a closure issue and this removes the need for a closure

    document.body.addEventListener('click', function(e) {
      var tgt = e.target;
      if (tgt.tagName === "IMG") {
        var audiosrc = tgt.getAttribute("data-audio");
        if (audiosrc) {
          var audio = new Audio(audiosrc);
          audio.play();
        }
      }
    })
    
    for (var i = 0; i < 4; i++) {
      var imgsrc = "niels" + i + ".png";
      var audiosrc = i + ".ogg";
      var image = document.createElement("IMG");
      image.setAttribute("data-audio", audiosrc)
      image.setAttribute("src", imgsrc);
      document.body.appendChild(image);
    }