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
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
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.