David Jones

Visibility api

The HTML5 visibility API lets the developer make adjustments to the application based on whether the user is currently viewing the webpage in their browser.

So why is this useful?

Some scenarios that this would come in handy are if your webpage uses timed AJAX calls they can be paused when the user is away from the page or video or audio can be paused. This will help your application become more efficient.

Lets have a look at how this can be achieved.

    var browserPrefixes = [ "", "webkit", "moz", "ms", "o" ],
    browser,
    hidden = true;

for( var i = 0; i < browserPrefixes.length; i++ ) {

    if( document[ browserPrefixes[ i ] + "Hidden" ] != undefined ) {
        browser = browserPrefixes[ i ];
    }
}

document.addEventListener( browser + 'visibilitychange', function() {
    hidden = document[ browser + "Hidden" ];
    document.title = hidden;
});

As you can see we need to check each browser because they all have their own prefixes. All we are doing here is looping round each prefix and seeing if the hidden variable is defined. If it is we now know the prefix to use when listening for the visibility change event.

Next we need to set up a event listener for the visibility change. In this example we are setting the title to either true or false depending on if the current tab is visible. If you try switching tabs you should this the title change.