Adam Silver Adam Silver - 7 months ago 81
Javascript Question

How can I pause all playing VideoJS instances on page when one is started?

I came up with this solution now:

var myPlayer1 = _V_("ID1");
var myPlayer2 = _V_("ID2");
...
...

var myFunc1 = function(){
var myPlayer1 = this;

myPlayer2.pause();
myPlayer3.pause();
myPlayer4.pause();
...
};
myPlayer1.on("play", myFunc1);

var myFunc2 = function(){
var myPlayer2 = this;

myPlayer1.pause();
myPlayer3.pause();
myPlayer4.pause();
...
};
myPlayer2.on("play", myFunc2);

...


Any other sane way to do it?

Thanks.

rk1 rk1
Answer

You can try this solution, assuming you use jQuery.

You might try to avoid pausing videos that are not currently playing. This can be done by adding another check in the loop - here all videos on the page are being paused whenever another one starts playing.

Also, there might be a better way to avoid the video ids ( ike $(this).player or something similar), but this does the job.

 $(".video-js").each(function (videoIndex) {
    var videoId = $(this).attr("id");

    _V_(videoId).ready(function(){
        this.on("play", function(e) {
            //pause other video
            $(".video-js").each(function (index) {
                if (videoIndex !== index) {
                    this.player.pause();
                }
            });
        });

    });
});