Created
November 6, 2013 21:43
-
-
Save mjc-gh/7344637 to your computer and use it in GitHub Desktop.
Page visibility jQuery API
This file contains hidden or 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, 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'); | |
}); | |
// TODO handle mobile browsers where we dont have either visibility API or focusin. setup | |
// interval to check document.hasFocus() | |
} | |
// 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