Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Detect Window / Tab lost focus
(function() {
var hidden = "hidden";
// Standards:
if (hidden in document) {
document.addEventListener("visibilitychange", onchange);
} else if ((hidden = "mozHidden") in document){
document.addEventListener("mozvisibilitychange", onchange);
} else if ((hidden = "webkitHidden") in document) {
document.addEventListener("webkitvisibilitychange", onchange);
} else if ((hidden = "msHidden") in document) {
document.addEventListener("msvisibilitychange", onchange);
} else if ('onfocusin' in document) {
// IE 9 and lower:
document.onfocusin = document.onfocusout = onchange;
} else {
// All others:
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
}
function onchange (evt) {
var v = 'visible';
var h = 'hidden';
var evtMap = { focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h };
evt = evt || window.event;
if (evt.type in evtMap) {
document.body.className = evtMap[evt.type];
} else {
if(this[hidden]) {
// lost focus
} else {
// gained focus
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment