Search code examples
javascriptjqueryvideo.js

Pausing all other videos, regardless of how many videos are on a page


So I'm using video.js on a multipage project that has pages with differing numbers of videos on each page. I want playing one video to pause any other video playing on the page. I've got it to work, but my code only works if it's made specifically to the page, as opposed to working on each page on its own.

HTML (example)

<video id="video5" poster="poster.png" class="video-js vjs-16-9 vjs-big-play-centered"
  data-setup='{
    "controls": true,
    "autoplay": false,
    "preload": "none"
  }'>
  <source src="video.mp4" type='video/mp4'>
</video>

JS

var player1 = videojs('video1');
var player2 = videojs('video2');
var player3 = videojs('video3');
var player4 = videojs('video4');
var player5 = videojs('video5');
var player6 = videojs('video6');

var players = [player1, player2, player3, player4, player5, player6];

players.forEach(function(player) {
  player.on('play', function() {
    console.log('test');
    players.forEach(function(pl) {
      if (pl !== player) {
        pl.pause();
      }
    })
  })
});

So this works fine if I have 6 videos with those coinciding id's. But if I have more or less, it breaks. Is there a way to format the JS to just pause anything by class as opposed to by id? I've tried ('.video-js').pause() but this throws an error.


Solution

  • NM, found the answer. Leaving this up so it's easier to find for people possibly.

    var medias = Array.prototype.slice.apply(document.querySelectorAll('audio,video'));
    medias.forEach(function(media) {
      media.addEventListener('play', function(event) {
        medias.forEach(function(media) {
          if(event.target != media) media.pause();
        });
      });
    });