How to play one html5 video on same page at a time

Hello,

Am trying to play one video at a time on same page. I have many videos display on same page from the server. When one video is playing and another video is click to play the first video playing should pause

<video src='.$vidVal.' controls loop type="video/mp4"></video>


$('video').bind('play', function (e) 
{
    var video = $('video');
    for(var i=0;i<video.length;i++)
    {
        if(video[i] != e.target)
        {
           video[i].pause();
        }
    }
});

The code above is not working, Kindly help provide working code

Looking forward for help.

Thanks

Well if you’re using jQuery 3, you should be using on instead of bind, as its deprecated.

Do the video elements exist in the source, or are they being dynamically added?

$('video').on('play', function(e) { 
   $("video").each(function (x) { 
     let loop = $(this).get(0);
     if(loop != e.target) { loop.pause(); }  
   });
});

Thanks for your help @m_hutley

The video elements are being added dynamically on page stroll.

The code do not work, more than one video still play at a time.

When one video is playing and when another video is click to play the first video should pause.

Okay, so you need to delegate the event. jQuery’s not particularly helpful at this, so i’m going to revert to vanilla JS on the outer layer and use Capturing instead of Bubbling (because Video events dont bubble above the media element, as they are unambiguous)

document.addEventListener("play", function (e) {		
   $("video").each(function (x) { 
     let loop = $(this).get(0);
     if(loop != e.target) { loop.pause(); }  
   });
}, true);

EDIT: I’m also going to clean up my code to only call get once. slaps own wrist

1 Like

I should clarify: jQuery does delegation just fine, but as far as i’m aware, it can only handle delegating events that are bubbling up; the video events not bubbling up make that problematic for jQuery.

Thanks so much @m_hutley

The code is working fine now. Only one video play at a time now.

Thanks, I really appreciate. More knowledge to you.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.