Skip to content

Instantly share code, notes, and snippets.

@mjc-gh
Created February 9, 2012 18:23
Show Gist options
  • Save mjc-gh/1781798 to your computer and use it in GitHub Desktop.
Save mjc-gh/1781798 to your computer and use it in GitHub Desktop.
Page Visibility API Wrapper with focus\blur failback
(function($){
var prop = 'VisibilityState';
var evt = 'visibilitychange';
var vendors = ['webkit', 'ms'];
var vendor;
function set_state(state){
$(window).trigger('visibilitychange', state);
$.visibilityState = state;
}
// detect property vendor prefixed property, if available
for (var i = 0; vendor = vendors[i]; i++){
if (vendors[i] + prop in document){
vendor = vendors[i];
prop = vendor + prop;
break;
}
}
// setup event handlers
if (vendor){
$(document).on(vendor + evt, function(){
set_state(document[prop]);
});
} else {
// not as cool failback -- this is functionally different than the visibilitychange event
// it's recommended you understand what makes the two different before using this code
$(window).on('focus', function(){
set_state('visible');
}).on('blur', function(){
set_state('hidden');
});
}
// set initial state
$.visibilityState = document[prop] || 'visible';
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment