Created
February 9, 2012 18:23
-
-
Save mjc-gh/1781798 to your computer and use it in GitHub Desktop.
Page Visibility API Wrapper with focus\blur failback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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