Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 188
  • Last Modified:

Why is my variable not initialised?

Take a look at the following code. It creates a page with a button, which when clicked opens a new window. That bit is working.

The onFocus event triggers when the original page gets the focus, and displays an alert box. That is working too.

However, the var "win" which has the reference to the new window is not initialised by the time the onFocus event fires, even though the window has been opened successfully. I'm not that used to Javascript, so I must be missing something pretty stupid. Any ideas?

<html>
<head>
<title>This is the opening page</title>
</head>

<script Language=JavaScript>

  var win = null;
  var nms = "Neil is initialised";

  function butOpenWin_onclick()
  {
    win = window.open("http://www.google.co.uk", "myWindow","resizable=yes");
  }

  function gotFocus()
  {
        alert("Got the onFocus event");
        if (!win) alert("win is not initialised");
    if (win && win.closed) alert("The window has closed");
    if (win && win.open) alert("The window is open");
  }
</script>


<body onfocus="gotFocus()">
<input type="button" value="Open" onClick="JavaScript: window.open('http://www.google.co.uk', 'newWindow')">
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
<p>Some text to click in............</p>
</body>
0
crescendo
Asked:
crescendo
1 Solution
 
Michael_CicognaCommented:
Hi!

I think your problem is rather easy to solve!

You are calling
    JavaScript: window.open('http://www.google.co.uk', 'newWindow')
in the OnClick event of the button.

You should replace it with
    butOpenWin_onclick
which should work then

Michael
0
 
crescendoAuthor Commented:
D'oh!!

I did that for testing, then wrote the functions, and never went back. I just assumed I'd got the functions wrong!

Many many thanks!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now