It is a common requirement in today’s highly interactive web applications to keep track if the browser window is currently in focus. Let me tell you one thing. If you take a look at the browser events and the very limited documentation, you might be tempted to believe that you are in safe hands. But thats not the case.
Catching the onbur and onfocus events is the most recommended way to know when a window gains or loses focus. But this does not work in all cases. The onfocus event is triggered correctly in almost all browsers. But onblur on the other hand is highly unpredictable. In Internet Explorer, every onfocus event is immediately followed by an onblur event even though the window is still in focus. On Firefox, the onblur will not be trigerred if the active element of the window is of input type.
Solution: IE has its custom events which works fine for it namely focusin and fosucout. For firefox, we need to check whether the active element has changed.
var isIE = (navigator.appName == "Microsoft Internet Explorer");
var hasFocus = true;
var active_element;
function setFocusEvents() {
active_element = document.activeElement;
if (isIE) {
document.onfocusout = function() { onWindowBlur(); }
document.onfocusin = function() { onWindowFocus(); }
} else {
window.onblur = function() { onWindowBlur(); }
window.onfocus = function() { onWindowFocus(); }
}
}
function onWindowFocus() {
hasFocus = true;
}
function onWindowBlur() {
if (active_element != document.activeElement) {
active_element = document.activeElement;
return;
}
hasFocus = false;
}
NB: I have tested mostly on IE 6+ and Firefox. So you might find my method incomplete for other browsers.
Update: This post has been updated (corrected) as per Lucent’s comment.
I was very excited to find this, but disappointed to find window.onfocusin/out do not fire in IE7. Perhaps this script could be modified to use document.onfocusin?
Thanks Lucent. You have a valid point there. I see that your suggession works fine and I am updating the post accordingly.
Very nice solution, thank you! While in my special case, I didn’t need to use the activeElement part, the rest seems to work fine in Safari 3.1 and Opera 9, too.
Hey dude, for some reason your code doesn’t work with me (IE6 / FF), any ideas?
PS: I’ve create a new solution that works for me, if you want you can take a look at it in my blog.
Regards.
Can you give me an example how to build this in a website?
Thx alot!
Thanks for putting this code out there! Needed a quick example and this site popped up first. Works wonderfully though you’re missing a ‘;’ on line 12 above.
Not working in safari