0

I have audio elements on my page to which I've added eventlisteners that listen for the "playing" event. If they are, I want to execute some stuff.

I'm also dynamically adding audio elements to my DOM (ajax fetch). However, for these elements that are newly added after the page load, the eventlsiteners do not work. I've looked into event delegation, I don't think I'm getting it right. Here's my current code [currently only applies listeners to elements loaded on page (re)load].

var audioFiles = document.getElementsByTagName('audio');

for (var i = 0; i < audioFiles.length; i++) {

    // function to execute if an audio file is played or resumed
    audioFiles[i].addEventListener("playing", function() {

        // save its ID in a variable
        var id = parseInt(this.id); // parseInt() turns this into an integer

        // then save the DOM element that was just played in a variable
        var filePlayed = $("#" + id);

        // then do some more things......
    }, true)
};
Mihkel Mark
  • 115
  • 1
  • 13

0 Answers0