Detect When Page is Not Visible Using JavaScript
Demonstration
See what happens when you minimise this page or jump to another browser tab.
You’ve been away, haven’t you!
Description
The Page Visibility API is an event driven API that lets you know when the HTML page is visible or in focus on the client side web browser. There are various uses for this such as ensuring you have the complete attention of the user or perhaps initiating an auto-save of any uncommitted data.
The demonstration on this page will log each time the page is made visible or hidden as well as changing the page title to say “Come Back!” and a message “You’ve been away, haven’t you!” that appears then fades out anytime the page comes back in to focus.
Further Uses and Ideas
- TBC
How it Works
Please find below a self-contained HTML snippet with inbuilt CSS and JavaScript
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Visibility API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var visibilityChange = (function (window) {
var inView = false;
return function (fn) {
window.onfocus = window.onblur = window.onpageshow = window.onpagehide = function (e) {
if ({focus:1, pageshow:1}[e.type]) {
if (inView) return;
fn("visible");
inView = true;
} else if (inView) {
fn("hidden");
inView = false;
}
};
};
}(this));
visibilityChange(function (state) {
var d = new Date();
var n = d.toLocaleTimeString();
document.getElementById("textoutput").innerHTML= n +': Page is ' + state + '<br />'+ document.getElementById("textoutput").innerHTML;
if (state=="hidden")
{
$("#message").fadeIn();
document.title = "Come Back!";
}
if (state=="visible")
{
$("#message").fadeOut(2000);
document.title = "Page Visibility API";
}
});
</script>
<style>
#message {
display: none;
}
</style>
</head>
<body>
<h1>Page Visibility API</h1>
<div id="message"><h2>You’ve been away, haven’t you!</h2></div>
<div id="textoutput"></div>
</body>
</html>
Relevant Links
Version History
Version | Date | Description |
---|---|---|
Version 1.0 | 10/11/2016 | Version 1 |