Ernest Delgado
hiddenand the enumeration visibilityState. The visibilityState property currently has four possible values: hidden, visible, prerender, and unloaded.
vendor-prefixed in Android Browser, where you’ll need to use prefixed versions such as webkitHiddenand webkitVisibilityState. All other supporting browsers (IE 10+, Firefox, Chrome, Safari) implement the un-prefixed versions.
As you might expect, the hidden attribute returns true when the document is not visible at all. Typically, this means that the document is either minimized, on a background tab, the OS's lock screen is up, etc. The attribute is set to false if any part of the document is at least partially visible on at least one display. In addition, to accommodate accessibility tools, the hidden attribute can be set to false when a tool such as a screen magnifier completely obscures the document, but is showing a view of it.
function getHiddenProp(){
var prefixes = ['webkit','moz','ms','o'];
// if 'hidden' is natively supported just return it
if ('hidden' in document) return 'hidden';
// otherwise loop over all the known prefixes until we find one
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
// otherwise it's not supported
return null;
}
isHidden(), to see if the document is visible.
function isHidden() {
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
}
hidden: the document is completely hidden from view
●visible: the document is at least partially visible on at least one display device
●prerender: the document is loaded off-screen and not visible (this value is optional; not all browsers will necessarily support it)
●unloaded: if the document is to be unloaded, then this value will be returned (this value is optional; not all browsers will necessarily support it)
// use the property name to generate the prefixed event name
var visProp = getHiddenProp();
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
document.addEventListener(evtname, visChange);
}
function visChange() {
var txtFld = document.getElementById('visChangeText');
if (txtFld) {
if (isHidden())
txtFld.value += "Tab Hidden!\n";
else
txtFld.value += "Tab Visible!\n";
}
}