How to pause video when click on new tab using javascript?

4.1k Views Asked by At

I'am working on video HTML Tag i want pause the audio when new Tab is open. Pls help to fix this issue.

<video autoplay onplay="clickplayer()" id="player" onended="endplayer()" fullscreen="true" controls onvolumechange="myFunction()"  ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">dik</video>
2

There are 2 best solutions below

0
On

The visibilitychange event is fired when the content of a tab has become visible or has been hidden.

You should detect tab visibility on visibilitychange event and pause video if tab is hidden.

var focused = true;
document.addEventListener("visibilitychange", function () {
  focused = !focused;
  if (!focused)
    document.getElementById("video").pause();
});
<video id="video" width="400" controls>
   <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>

0
On

You need to detect the window de-focus event first to do so. Here is an example:

HTML:

 <video id="video" width="400" controls>
   <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
 </video>

JS:

document.addEventListener("visibilitychange", onchange);
function onchange (evt) {
   document.getElementById("video").pause();
}

You can find full example Here

Note that, same method applies to Audio tags as well.