Friday, January 20, 2012

HTML5: Page Visibility API

HTML5 has introduced a page Visibility API. As the name suggests, this API give information about whether or not the page is visible to the user. This API provides a visibilitychange event which can be used to notify when the page changes from visible to hidden or hidden to visible.

Note: In Internet Explorer, this event is called msvisibilitychange and in Chrome it’s called webkitvisibilitychange.

Following is the cross browser way for using this API:

var EventHandler = {
    addHandler: function(element, type, handler){
        if (element.addEventListener){
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent){
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
        }
    },
    removeHandler: function(element, type, handler){
        if (element.removeEventListener){
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent){
            element.detachEvent("on" + type, handler);
        } else {
            element["on" + type] = null;
        }
    }
};

function handleVisibilityChange(){
    if (document.hidden || document.msHidden || document.webkitHidden){
        alert("Page is now hidden.");
    } else {
        alert("Page is now visible.");
    }
}

EventHandler.addHandler(document, "msvisibilitychange", handleVisibilityChange);
EventHandler.addHandler(document, "webkitvisibilitychange", handleVisibilityChange);

Browser Support:

  • Internet Explorer (10+)
  • Chrome (12+)

1 comment:

A.I. said...

You forget about moz prefix. It will be better to use wrapper library like Visibility.js and forget about vendor prefixes and browser without support https://github.com/ai/visibility.js