Pause Video When User Leaves Tab - Javascript

Pause Video When User Leaves Tab – HTML & Javascript

0
(0)

In this article, we are going to teach you, how you can pause a video on your website as soon as the user leaves the tab using Javascript. Also, we will play the video when the user comes back again on the site.

First, you need to create a video tag.

<video src="media/test.mp4" style="width: 100%;" controls id="video"></video>
  • The src attribute will be the path of the video file.
  • The width is 100% so the video will not overflow the webpage.
  • controls attribute to display play/pause, volume up/down, and other controls.
  • Unique ID so it can be accessible in Javascript.

At this point, you will see a video player on your website. If you play the video and move to another tab, the video will keep playing in the background. So the following Javascript code will make sure the video gets paused as soon as the user leaves the tab, and play the video back when the user re-enters the tab.

const video = document.getElementById("video");

document.addEventListener("visibilitychange", function () {
    if (document["hidden"]) {
        video.pause();
    } else {
        video.play();
    }
});

Refresh the page and play the video again. Now if you move to another tab, you will see that the video automatically gets paused and resumed from the same point where it was left when you re-open the tab.

Kindly login or create a new account to download the files.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





Please disable your adblocker or whitelist this site!