Entry
How do I automatically close window if it loses focus?
I implemented this technique to automatically close popup windows on my site. However in IE5+ the po
Aug 27th, 2001 11:30
Betty Cantilever, Martin Honnen, Justin Stach, S M,
If you use
<BODY ONBLUR="window.close();">
the window will close when the BODY looses focus. That happens when you
click outside the window which is the effect you want but it happens
too when an gui element (a form field, a link etc) in the window gains
focus. So the above is helpful for simple message windows which you
popup and then close automatically when the user defocusses the window
but it is not helpful if you open a window with a document inside where
the user needs to access gui elements (form fields, links etc) inside
the window as then the window would close when not intended.
Fortunately with NN4 there is a way to solve that dilemma as the window
can capture focus events and then if you setTimeout on the window.close
() cancel that call.
IE4+ and NN6 can't capture the focus event as it doesn't bubble but you
can loop through all elements in the document body and set the onfocus
handler to cancel the timeout you set for closing the window in onblur.
That way the following page when opened in a popup window closes itself
when someone clicks outside of the window but remains open when someone
clicks inside the window:
<HTML>
<HEAD>
<SCRIPT>
var tid;
function closeWin () {
tid = setTimeout('window.close()', 30);
}
function cancelCloseWin (evt) {
clearTimeout(tid);
}
window.onblur = closeWin;
if (document.layers) {
window.captureEvents(Event.FOCUS);
window.onfocus = function (evt) {
cancelCloseWin(tid);
routeEvent(evt);
};
}
function changeOnFocusHandlers () {
if (document.all) {
for (var e = 0; e < document.body.all.length; e++)
if (document.body.all[e].onFocus) {
document.body.all[e].oldOnFocus =
document.body.all[e].onFocus;
document.body.all[e].onFocus = function (evt) {
cancelCloseWin(evt);
this.oldOnFocus(evt);
};
}
else
document.body.all[e].onFocus = cancelCloseWin;
}
else if (document.getElementsByTagName) {
var all = document.body.getElementsByTagName('*');
for (var e = 0; e < all.length; e++)
if (all[e].getAttribute('onfocus'))
all[e].onfocus = new Function ('evt',
'cancelCloseWin(evt); ' + all[e].getAttribute('onfocus')
+ '; return true;');
else
all[e].onfocus = cancelCloseWin;
}
}
</script>
</head>
<BODY ONLOAD="changeOnFocusHandlers();">
<FORM NAME="aForm">
<INPUT TYPE="text" NAME="aField" ONFOCUS="window.status = 'enter name'">
</form>
</body>
</html>