Skip to content

Instantly share code, notes, and snippets.

@ramonchito2
Created January 27, 2016 21:36
Show Gist options
  • Save ramonchito2/ab68c5a355ee9e809269 to your computer and use it in GitHub Desktop.
Save ramonchito2/ab68c5a355ee9e809269 to your computer and use it in GitHub Desktop.
Check to see if the current tab is visible
// CHECK TO SEE IF THE CURRENT TAB IS VISIBLE
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
console.log('I have been hidden');
visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
console.log('Moz has been hidden');
visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
console.log('Ms has been hidden');
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
console.log('Webkit has been hidden');
visibilityChange = "webkitvisibilitychange";
}
// IF CURRENT TAB BECOMES VISIBLE AGAIN, DO SOMETHING
if (typeof document.addEventListener !== "undefined" ||
typeof document[hidden] !== "undefined") {
// Handle page visibility change
document.addEventListener(visibilityChange, function(){
if( document[hidden] ) {
console.log('document hidden');
} else {
console.log('document visible');
}
}, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment