I have 10 audio players with simple html audio tags on a html5 page. No jquery, no special audio js plugins, etc...
Does anyone has a simple script in js to pause al
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);
$("audio").on("play", function() {
var id = $(this).attr('id');
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
$("video").on("play", function() {
var id = $(this).attr('id');
$("video").not(this).each(function(index, video) {
video.pause();
});
});
You can even try this solution, if you don't want to loop through
var previuosAudio;
document.addEventListener('play', function(e){
if(previousAudio && previousAudio != e.target){
previousAudio.pause();
}
previousAudio = e.target;
}, true);
I don't know if it is because of Chrome updates, but the previous answers did not work for me. I modified a bit of the code here and came up with this:
document.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
I don't know why, but the widow.addEventListener
was not working for me, but I liked the idea of having the currentPlaying
variable stored in the window
element instead of having to create it outside of the listener prior to using it.
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.
This makes a bit more sense, unless you intend to start with multiple elements playing at the same time.
window.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying)
{
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);