Detect When Page is Not Visible Using JavaScript


See what happens when you minimise this page or jump to another browser tab.

You’ve been away, haven’t you!


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>
<meta charset="utf-8">
<title>Page Visibility API</title>
<script src=""></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;
			inView = true;
		} else if (inView) {
			inView = false;
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")
	document.title = "Come Back!";
if (state=="visible")
	document.title = "Page Visibility API";
#message {
	display: none;
	<h1>Page Visibility API</h1>
	<div id="message"><h2>You’ve been away, haven’t you!</h2></div>
	<div id="textoutput"></div>

Relevant Links

Page Visibility API

Version History

Version Date Description
Version 1.0 10/11/2016 Version 1

Comments For This Page

You should try to open a new tab, go to it and return and check out what happens to it next.
By Nobody on 6th February 2019

Add your own comment below and let others know what you think:

Share This Page

Share this page with others using one of the methods below. Telling others about Daft Logic is good and we appreciate your support!