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

 

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:

 

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Disclaimer:

As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.