Detect page leave – HTML & Javascript

In this article, we are going to teach you, how you can detect page leave event using Javascript. Sometimes we would want some action, like an AJAX call when the user leave the page and move to another tab. Or minimize the browser.

We will create a simple video tag. And we will pause the video 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.

So that’s how you can detect page leave event on your website using simple and plain Javascript. You can check out our other Javascript tutorials to learn more about Javascript.

[wpdm_package id=’1559′]

2 Replies to “Detect page leave – HTML & Javascript”

Comments are closed.