Last active
August 29, 2015 13:57
-
-
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.
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
/** | |
* 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