Home > OS >  how to play/pause, if there is multiple videos on a page
how to play/pause, if there is multiple videos on a page

Time:02-26

I have a lot of video tags on a page. I need to play/pause an element if it was clicked on, and pause the previous element ,if it is playing. When I clicked on one element after page loading, the clicked element was played but when I clicked at the second time, on the same video, it was not paused.

<video class='vsingle' src='01.mp4' poster='01.jpg' preload='none' controls></video>
<video class='vsingle' src='02.mp4' poster='02.jpg' preload='none' controls></video>
<video class='vsingle' src='03.mp4' poster='03.jpg' preload='none' controls></video>

$('.vsingle').on('click', function(){
    if($(this).hasClass('active')){
        $(this).trigger('pause').removeClass('active');
    }
    else{
        $('.active').trigger('pause').removeClass('active');
        $(this).trigger('play').addClass('active');
    }
});

CodePudding user response:

The jQuery method .trigger() deals with standard Events. It does not recognize Events that are exclusive to Web APIs like MediaElement interface to which the <video> tag belongs to. So events "pause" and "play" cannot be triggered with any jQuery method. Moreover, "pause"/"play" events are triggered by .pause() and .play() methods. To use them, they'll need to suffixed to a plain JavaScript object of a <video> tag. jQuery $(objects) cannot use plain JavaScript methods and vice versa.

$('video').on('click', function(e) {
  let vids = $.makeArray($(this).siblings('video'));

  vids.forEach(vid => {
    vid.pause();
    vid.classList.remove('active');
  });

  $(this).toggleClass('active');
  if ($(this).is('.active')) {
    this.play();
  } else {
    this.pause();
  }
});
video {
  height: 30vh;
  cursor: pointer;
}

.active {
  outline: 2px solid blue
}
<video src='https://glpjt.s3.amazonaws.com/so/av/vs34s3.mp4'></video>
<video src='https://glpjt.s3.amazonaws.com/so/av/vs34s3.mp4'></video>
<video src='https://glpjt.s3.amazonaws.com/so/av/vs34s3.mp4'></video>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related