tags:

views:

162

answers:

4

I am trying to open new window from hyperlink using java script and then auto close it in five seconds. It either closes right away or doesn't close at all. Here are some samples of code I was using:

"function closeOnLoad(myLink){var newWindow=window.open(myLink);newWindow.onload=SetTimeout(newWindow.close(),5000);}" + LinkText + ""

A: 

To unload is the unload() function. Here you have an example.

Elzo Valugi
+1  A: 

you need to use what is called a 'closure' to wrap the timeout in. It's like the function to timeout and then close is wrapped within another function.

I won't go into detail here, but lookup javascript and closures and play around to see how they work.

Here's a link to help get you started: http://www.jibbering.com/faq/faq%5Fnotes/closures.html

Evernoob
+1  A: 

The window closing code should be in the window's code:

$(document).ready(function() {
    setTimeout(function() {
        window.close();
    },5000);
})

BUT, you will get a popup asking for the user to confirm if you try & close the popup that way.

Julian Aubourg
assuming of course that he's running jQuery with the sample that you have provided.
Evernoob
Julian Aubourg
+2  A: 

You're better off closing the window from the parent instead of defining an onload handler within the child. Due to security restrictions, you simply may not have access to modify child window events.

function closeOnLoad(myLink)
{
  var newWindow = window.open(myLink);
  setTimeout(
             function()
             {
               newWindow.close();
             },
             5000
            );
  };
}
David Andres
Thanks, this does what I was trying to do.
aleks2009