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>
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>
Share
edited Jan 20, 2017 at 18:49
Mohammad
21.5k16 gold badges56 silver badges84 bronze badges
asked Jan 9, 2017 at 10:23
chozhanchozhan
1812 silver badges17 bronze badges
1
- Do you want pause audio and keep video playing or both pause? – Mohammad Commented Jan 10, 2017 at 13:28
2 Answers
Reset to default 6You 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./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.
The
visibilitychange
event is fired when the content of a tab has bee 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./html/mov_bbb.mp4" type="video/mp4">
</video>