Tutorials

Tutorials about HTML, CSS, PHP, Javascript, and Photoshop

  • Home
    Home This is where you can find all the blog posts throughout the site.
  • Categories
    Categories Displays a list of categories from this blog.
  • Tags
    Tags Displays a list of tags that has been used in the blog.
  • Archives
    Archives Contains a list of blog posts that were created previously.
  • Login

HTML5 Page Visibility API

by in Photoshop
  • Font size: Larger Smaller
  • Hits: 4374
  • 0 Comments
  • Subscribe to this entry
  • Print
4374

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, In earlier days. Being a programmer, sometime this numbers goes above 25-30, I normally have 10-15 tabs open at a time

Why This API?

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

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 isDocument. VisibilityStateAnd second one isDocument. Hidden

Document. VisibilityStateHolds 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. HiddenIs 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

Document. AddEventListener('visibilitychange', function(event) {
  if (. Document. Hidden) {
    // The page is visible
  }Else {
   // The page is hidden 
  }
});

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:

// Get Browser-Specifc Prefix
function getBrowserPrefix() {
  
  // Check for the unprefixed property. If ('hidden' in document) {
    return null;
  }// All the possible prefixes. 'ms', 'o', var browserPrefixes = ['moz', 'webkit'];

  for (var i = 0; i < browserPrefixes. Length; i++) {
    var prefix = browserPrefixes[i] + 'Hidden';
    if (prefix in document) {
      return browserPrefixes[i];
    }
  }// The API is not supported in browser. Return null;
}// Get Browser Specific Hidden Property
function hiddenProperty(prefix) {
  if (prefix) {
    return prefix + 'Hidden';
  }Else {
    return 'hidden';
  }
}// Get Browser Specific Visibility State
function visibilityState(prefix) {
  if (prefix) {
    return prefix + 'VisibilityState';
  }Else {
    return 'visibilityState';
  }
}// Get Browser Specific Event
function visibilityEvent(prefix) {
  if (prefix) {
    return prefix + 'visibilitychange';
  }Else {
    return 'visibilitychange';
  }
}

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

// Get Browser Prefix
var prefix = getBrowserPrefix();
var hidden = hiddenProperty(prefix);
var visibilityState = visibilityState(prefix);
var visibilityEvent = visibilityEvent(prefix);

document. AddEventListener(visibilityEvent, function(event) {
  if (. Document[hidden]) {
    // The page is visible
  }Else {
   // The page is hidden 
  }
});

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. We can show, In a similar mannerHTML NotificationOnly 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 TitleView Demo
  • Demo 2: This demo demonstrates how we can restrict polling data from the server when page is inactive.  

But only when the user is looking at the page, In this demo, we will examine how we can restrict polling the server for fresh information. 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

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

The JavaScript

<script type="text/javascript">
    
	// Get Browser Prefix
	var prefix = getBrowserPrefix();
	var hidden = hiddenProperty(prefix);
	var visibilityState = visibilityState(prefix);
	var visibilityEvent = visibilityEvent(prefix);
	
	var timer = null;
	
	function increaseVal() {
		var newVal = parseInt($('#valueContainer'). Text()) + parseInt(1);
		$('#valueContainer'). Text(newVal);
		document. Title = newVal + ': Running'; 
		
		timer = setTimeout(function() {
			increaseVal();
        }1);
	}// Visibility Change 
	document. AddEventListener(visibilityEvent, function(event) {
		  if (document[hidden]) {
			  clearTimeout(timer);
			  var val = parseInt($('#valueContainer'). Text());
			  document. Title = val + ': Pause'; 
		  }Else {
			  increaseVal();  
		  }
	});
	
	increaseVal();
	
</script>

View Demo

Browser Support

Then I would advise looking at, If you wan to look at browser support for for this APICan I use?But to programmatically find out for the browser support I would suggest taking this article toDetect Support for Various HTML5 FeaturesSo 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. It can be easily integrated with your existing application which may positively affect your user experience, This way. Now we can control how our websites will behave when our website is hidden to user, Ultimately

Read more: HTML5 Page Visibility API

0
Trackback URL for this blog entry.

Comments

  • No comments made yet. Be the first to submit a comment

Leave your comment

Guest Wednesday, 08 July 2020

Testimonial

Thank you so much! We are very happy with our new website. It is easy to use and all of our customers tell us, they love it.

Contact Us

  • 13245 Atlantic Blvd. #4352
    Jacksonville, FL 32225
  • 904-240-5823