Skip to content

Instantly share code, notes, and snippets.

@ryantbd
Last active August 29, 2015 13:57
Show Gist options
  • Save ryantbd/9544950 to your computer and use it in GitHub Desktop.
Save ryantbd/9544950 to your computer and use it in GitHub Desktop.
Simple function to monitor tab visibility, do something while current tab is active / hidden.
/**
* Able to monitor tab visibility, do something while current tab is active / hidden.
* Works also on mobile browsers
* @return {[type]} [description]
*/
var TabControl = {
tabVisibilityChanged: function () {
if (this.tabIsHidden()) {
// tab is hidden
} else {
// tab is active
}
},
getHiddenProp: function () {
var prefixes = ['webkit','moz','ms','o'];
if ('hidden' in document) return 'hidden';
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
return null;
},
monitorTabVisibility: function () {
var visProp = this.getHiddenProp(),
self = this;
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
document.addEventListener(evtname, function () {
self.tabVisibilityChanged();
});
}
},
tabIsHidden: function () {
var prop = this.getHiddenProp();
if (!prop) return false;
return document[prop];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment