Skip to content
Advertisement

Do I need multiple event listeners for multiple audio elements-JavaScript?

I’m writing a silly page where I have 5 audio elements named myAudio1 thru myAudio5, and I want to display hello/goodbye messages when each of these audios are played/ended.

My current (certainly not the best) approach is having a JavaScript snippet for each of my audio tags: (this is for the first one)

var aud1 = document.getElementById("myAudio1");
aud1.onplay = function() {
console.log("myAudio1 says hello");
};
aud1.onended = function() {
console.log("myAudio1 says goodbye");
};

so I have five of these snippets with their own identifiers, all the way to myAudio5.
Apparently it’s a long and cumbersome approach, so I tried to simplify it and came up with this:

var audList = document.getElementsByTagName("audio");
console.log(audList.length);
for (var i = 0; i < audList.length; i++) {
  audList[i].addEventListener("load", audCheck, false);
}

function audCheck(e) {
    var aud = e.target;
    var audID = e.target.id;
    aud.onplay = function() {
        console.log(audID+" says hello");
    };
    aud.onended = function() {
        console.log(audID+" says goodbye");
    };
}

For whatever reason it’s not working (Help! http://jsfiddle.net/8176ccnk/); if it did, I would wonder if creating multiple event listeners is a necessity in these kind of scenarios, where the event handler itself sort of acts like an event listener. (I don’t think having one event handler that handles all child audio DOM events at the parent DOM level works…)
In general, what’s the best way of interacting with DOMs during these events?

Advertisement

Answer

There is no load event in the media events so your handler audCheck is not getting called.

You can directly add the start/stop/ended listeners

var audList = document.getElementsByTagName("audio");
console.log(audList.length); //prints out how many audio elements there are
for (var i = 0; i < audList.length; i++) {
    audList[i].addEventListener("play", onPlay, false);
    audList[i].addEventListener("ended", onEnded, false);
}
function onPlay(e) {
    console.log(e.target.id + " says hello");
};
function onEnded(e) {
    console.log(e.target.id + " says goodbye");
};

Demo: Fiddle

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement