Advertisement
Scroll to top

In earlier days, we had browsers that did not feature tabbed browsing, but today when you look at all browsers available, we can see that all browsers offer that. Being a programmer, I normally have 10-15 tabs open at a time, sometime this numbers goes above 25-30.

Why This API?

Earlier, it was not possible to determine which tab is active and which was not, but with the help of the HTML5 Visibility API, we can detect whether our visitor is looking at our web page or not. 

In this tutorial we will understand how to deal with HTML5 Visibility API and one simple demo to discover the status of the our page. In this demo we will alter the document title based on Status of Page Visibility.

Checking Visibility Status of Page

With the launching of this API we have welcomed two new document property which does two different functions. The first one is document.visibilityState and second one is document.hidden.

document.visibilityState holds four different values which are as below:

  • hidden: Page is not visible on any screen
  • prerender: Page is loaded off-screen and not visible to user
  • visible: Page is visible
  • unloaded: Page is about to unload (user is navigating away from current page)

document.hidden is boolean property, that is set to false if page is visible and true if page is hidden.

Now we can control how our websites will behave when our website is hidden to user.

Right away we know about our availability properties, but now it's time to listen to the event so that we can be notified about the new condition of the page visibility. This is done via the  visibilitychange event. We will see a quick demo on how to deal with this event.

1
document.addEventListener('visibilitychange', function(event) {
2
  if (!document.hidden) {
3
    // The page is visible.

4
  } else {
5
   // The page is hidden. 

6
  }
7
});

This code is simply a basic instance of utilizing this event and discover the current status of webpage. But to let you know that both these properties and method should be used vendor prefixed, because these events and properties are vendor-prefixed in some of the browsers. Now we will see the same code in a cross browser manner:

1
// Get Browser-Specifc Prefix

2
function getBrowserPrefix() {
3
  
4
  // Check for the unprefixed property.

5
  if ('hidden' in document) {
6
    return null;
7
  }
8
9
  // All the possible prefixes.

10
  var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];
11
12
  for (var i = 0; i < browserPrefixes.length; i++) {
13
    var prefix = browserPrefixes[i] + 'Hidden';
14
    if (prefix in document) {
15
      return browserPrefixes[i];
16
    }
17
  }
18
19
  // The API is not supported in browser.

20
  return null;
21
}
22
23
// Get Browser Specific Hidden Property

24
function hiddenProperty(prefix) {
25
  if (prefix) {
26
    return prefix + 'Hidden';
27
  } else {
28
    return 'hidden';
29
  }
30
}
31
32
// Get Browser Specific Visibility State

33
function visibilityState(prefix) {
34
  if (prefix) {
35
    return prefix + 'VisibilityState';
36
  } else {
37
    return 'visibilityState';
38
  }
39
}
40
41
// Get Browser Specific Event

42
function visibilityEvent(prefix) {
43
  if (prefix) {
44
    return prefix + 'visibilitychange';
45
  } else {
46
    return 'visibilitychange';
47
  }
48
}
49

We have all browser prefixed properties and event is ready to apply. Now we will change our previous code accordingly.

1
// Get Browser Prefix

2
var prefix = getBrowserPrefix();
3
var hidden = hiddenProperty(prefix);
4
var visibilityState = visibilityState(prefix);
5
var visibilityEvent = visibilityEvent(prefix);
6
7
document.addEventListener(visibilityEvent, function(event) {
8
  if (!document[hidden]) {
9
    // The page is visible.

10
  } else {
11
   // The page is hidden. 

12
  }
13
});

Where Can We Use This API?

There are a number of different scenarios where we can consider using this API.

  1. Imagine you are on the dashboard the page and page is polling details from some RSS feed or API on regular interval say two minutes. So we can restrict call to the RSS feed or API if page is not visible to the user (i.e., the user is not actually looking at page).
  2. For and image slider. we can limit movement of slider images when page is hidden.
  3. In a similar manner, we can show HTML Notification only when page is hidden to the user.

Up to here we have seen code to use HTML5 Page Visibility API, it's time for some action right away.

Demonstration

  • Demo 1: This demonstration presents the use of Page Visibility API to change Page Title. View Demo
  • Demo 2: This demo demonstrates how we can restrict polling data from the server when page is inactive. 

In this demo, we will examine how we can restrict polling the server for fresh information, but only when the user is looking at the page. I am assuming that jQuery is already included in your page. Here we will increase only the count, but this can be replaced with real server polling instead.

The HTML

1
<!-- This element will show updated count -->
2
<h1 id="valueContainer">0</h1>

The JavaScript

1
<script type="text/javascript">
2
    
3
	// Get Browser Prefix

4
	var prefix = getBrowserPrefix();
5
	var hidden = hiddenProperty(prefix);
6
	var visibilityState = visibilityState(prefix);
7
	var visibilityEvent = visibilityEvent(prefix);
8
	
9
	var timer = null;
10
	
11
	function increaseVal() {
12
		var newVal = parseInt($('#valueContainer').text()) + parseInt(1);
13
		$('#valueContainer').text(newVal);
14
		document.title = newVal + ': Running'; 
15
		
16
		timer = setTimeout(function() {
17
			increaseVal();
18
        }, 1);
19
	}
20
	
21
	// Visibility Change 

22
	document.addEventListener(visibilityEvent, function(event) {
23
		  if (document[hidden]) {
24
			  clearTimeout(timer);
25
			  var val = parseInt($('#valueContainer').text());
26
			  document.title = val + ': Pause'; 
27
		  } else {
28
			  increaseVal();  
29
		  }
30
	});
31
	
32
	increaseVal();
33
	
34
</script>

View Demo

Browser Support

If you wan to look at browser support for for this API, then I would advise looking at Can I use?. But to programmatically find out for the browser support I would suggest taking this article to Detect Support for Various HTML5 Features. So far we have really good support for this API in almost all major and latest browsers.

Conclusion

I would say that we have had a very good API which included only two properties and just one event. This way, it can be easily integrated with your existing application which may positively affect your user experience. Ultimately, now we can control how our websites will behave when our website is hidden to user.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.