Onblur and Onfocus

How can I close automatically a window which has been
opened with open.window ?
Who is Participating?
nettromConnect With a Mentor Commented:
ah... :)

<script type="text/javascript">
var myWindow;

function openWindow(myURL) {
  if(myWindow && !myWindow.closed) {
    myWindow.location = myURL;
  } else {
    myWindow = window.open('myURL', 'my_window');
return false;

function closeWindow() {
  if(myWindow && !myWindow.closed) {

call the script by:

<a href="link_for_those_without_javascript.html"
  onclick="return openWindow('my_url.html');">link text</a>

and then use either:

window.onfocus = closeWindow;


<body onfocus="closeWindow()">

the onfocus-attribute to BODY doesn't validate as HTML 4.0 so if you want it to validate you'll have to use your own custom DTD and a DOCTYPE that points to it (but it works in both IE4/5 & Netscape 4.x).
open.window is Microsoft's Jscript if I remember correctly.

when you open the window in JavaScript the return value from window.open() is the new window, which you then can manipulate.  make sure you keep that return value by assigning it to a variable.  e.g:

myWindow = window.open( ... );

then you can simply do:


you mention onblur() and onfocus(), when is it you want the close to trigger?
us111Author Commented:
Do you know how this works ?

window.onblur=handler-func  defining the handler directly
window.onblur();  an explicit invocation of the handler

In fact, I wish to open a new window (y) with window.open and then
when I click into the main window (x), the window (y) closes itself
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.