html5 – Video tag disconnect the previous player if a new one is started

Question:

On the html page there are the usual standard html5 players, but the problem is that if, for example, 1 player is running, that is, a video is played and when you click on another player, it also starts playing! How to implement that when you click on another player, the one that is playing stops?

Answer:

To do this, you need to use JavaScript, which will first stop unnecessary players (for example, all players on the page), and then start the current one.

There are two sides to the question – how to do it correctly, and literally as you asked in the question ("when you click on the player").

If you have controls display enabled, this is done correctly with media events . Here's some sample JavaScript using the jQuery library:

$(function() {
  $("video")[0].onplay = function () {
      var that = this;
      $('video').each(function () {
          if (this !== that) {
             this.pause();
          }
      });
  };
})

An example of how it works can be seen here in this feed on the JSFiddle .

If you have no other option but to track mouse clicks, you need to catch the onclick event:

$(function() {
  //При щелчке на любой элемент video
  $('video').on('click', function () {

      //Останавливаем все другие video
      $('video').each(function () {
          this.pause();
      });

      //И запускаем только текущий
      this.play();
  });
})

An example of how it works can be seen in this feed on the JSFiddle .

Depending on the mechanics of your web interface, the implementation may differ, but the idea remains the same.

In some cases (problems with the video tag with controls enabled), it may be worth not tracking click, but enabling playback on the mouseover event:

$(function() {
  $('video').on('mouseover', function () {
      $('video').each(function () {
          this.pause();
      });
            this.play();
  });
})
Scroll to Top