Since originally writing this answer, a new specification has reached working draft status thanks to the W3C. The Page Visibility API now allows us to more accurately detect when a page is hidden to the user.
Current browser support:
- Chrome 13
- Internet Explorer 10
- Firefox 10
- Opera 12.10 [read notes]
The following code makes use of the API, falling back to the less reliable blur/focus method in incompatible browsers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | (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); // IE 9 and lower: else if ('onfocusin' in document) document.onfocusin = document.onfocusout = onchange; // All others: else window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange; function onchange (evt) { var v = 'visible', h = 'hidden', 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 document.body.className = this[hidden] ? "hidden" : "visible"; } })(); |
onfocusin
and onfocusout
are required for IE 9 and lower, while all others make use of onfocus
and onblur
, except for iOS, which uses onpageshow
and onpagehide
.