multiple audio html : auto stop other when current is playing with javascript
Instead of looping over all audio tags on a page and pausing them, you can store a reference to the currently playing element, and have only that one pause when playing another.
document.addEventListener("play", function(evt) {
if(this.$AudioPlaying && this.$AudioPlaying !== evt.target) {
this.$AudioPlaying.pause();
}
this.$AudioPlaying = evt.target;
}, true);
Mixing both previous answers that didn't work, i've used that. I just added && window.$_currentlyPlaying != evt.target
and all is working.
Also i've created a gist with this and other goodies for audio tags. javascript-audio-tags
window.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
you can use event delegation. Simply listen to the play event in the capturing phase and then pause all video file, but not the target one:
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
}
}
}, true);