Thursday, October 26, 2006

Incorrect behavior of window.onblur event under IE and a workaround

In Internet Explorer window.onblur event is implemented incorrectly (as opposed to Firefox/Mozilla browsers). It is wrongly fired when focus is switched between HTML elements *inside* a window.
Suppose you're trying to automatically close a popup window when focus is switched to another (main) window (a common task). As a result of the described bug, clicking on any element *inside* a popup window or trying to select something there will also close a popup.
Below is a workaround.

var active_element;
var bIsMSIE;

function initiateSelfClosing() {
if (navigator.appName == "Microsoft Internet Explorer") {
active_element = document.activeElement;
document.onfocusout = closeWnd;
bIsMSIE = true;
else { window.onblur = closeWnd; }

function closeWnd() {
if (window.opener != null) {
if (bIsMSIE && (active_element != document.activeElement)) {
active_element = document.activeElement;
else {


<body onload="initiateSelfClosing()">

Your stuff