Videojs – Play and Pause multiple videos example

How to play only 1 video and pause all the others?

Vue js:

This is where you put your video players.

The “:poster” will just be the image you receive from your axios request. It helps load faster the players(by not loading the actual video).

 <video
:id="index"
:ref="'video_' + data.id"
class="video-js vjs-big-play-centered"
width="500"
height="450"
:poster="data.video_pictures[1].picture"
data-setup='{"controls": true, "autoplay": false, "preload": "auto"}'
>
<source :src="data.video_files[1].link" type="video/mp4" />
<p class="vjs-no-js">
To view this video please enable JavaScript, and consider upgrading to a
web browser that
<a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
</p>
</video>

Add this just above your export default vue component:

import videojs from 'video.js';
import 'video.js/dist/video-js.css';


export default {

}

Now the magic, no idea if you have noticed but we created a dynamic :ref in the video player itself by doing this:

:ref="'video_' + data.id"

The data.id will simply be the id of your video(from the axios request).

All we have to do now is create a button with a PLAY method:

 <button @click="play('video_' + data.id)"></button>

When the user clicks on the button, the play() method will be called as:

play(id) {
const keys = Object.keys(this.response.videos);
var self = this;
videojs(this.$refs[id][0].playerId).ready(function(){
keys.forEach((key, index) => {
let videoToPause = 'video_' + self.response.videos[index].id
if ('video_' + self.response.videos[index].id === id) {
self.$refs[id][0].play();
} else {
self.$refs[videoToPause][0].pause();
}
});
});

)

Why do I use var self = this; ?

The reason is because the foreach loop will happen inside the scope of  videojs(this.$refs[id][0].playerId).ready(function(){ and in order for me to call my methods outside this scope is to use var self = this; and start calling my response data with “self” rather than “this”.

Using video js can really be challenging and this is why I decided to create this short tutorial that shows you how to pause multiple videos when you play another one anywhere on your page.

Enjoy!

Kollox Team