" // write HTML to new window document newWindow.document.write(newContent); newWindow.document.close(); // close layout stream } newWindow.focus(); }
 JavaScript & HTML Tips
Feature highlight: Window Creation
Credit: Imagenation

Using windowOpen() to create a brand new window if it doesn't already exist; otherwise just bring it to the foreground.

Not to belabor a point but creating and interacting with browser windows is becoming increasingly important; so this tip looks at the details of creating a new window with your own dynamically issued content. Click the button below:

The following code does most of the dirty work here:

var newWindow= "";
function makeNewWindow() {
  if (newWindow == "" || newWindow.closed) {
    newWindow = window.open("","","status,height=400,width=500,resizable")
  // assemble content for new window
    var newContent = "<HTML><HEAD><TITLE>New Window</TITLE></HEAD>"
    newContent += "<BODY><H1>Pictures like these can be seen at <a
       href='http://edworlds.neelsplace.com' target='_blank'>Click here</a></H1>"
    newContent += "<img src='images/javelin.jpg'><script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-4281076-1"); pageTracker._initData(); pageTracker._trackPageview(); </script></body></HTML>"
  // write HTML to new window document
    newWindow.document.close(); // close layout stream

There is a lot trickiness buried in such short code. First, you must declare the var newWindow outside of the function makeNewWindow and assign it a blank value; otherwise different browsers losetrack of the window. Next, you have to test if the window already exists. We have seen this before in the tip on windows interactions. Again, cautious coding requires at least two tests-
 if (newWindow != null || newWindow.closed)
the advantage is less debugging time on older browsers. Finally we use the windowOpen("", "", "..settings..") form of the windowOpen routine. This opens a blank window after we fill it with newWindow.document.writes and then close it. Curiously this action causes the browser to do a flush input stream and actually create the window. The final chunk of code, newWindow.focus(), brings the new window to the foreground for review and or editing.

It really helps to understand the basics of dynamically creating your own windows on the fly- there are so many situations when you need to do so - pop-up an enlargement of a catalog item, get more detailed user reponses, display detail report info ... the list is long.

Top of Page  Tutorials Home  JavaScript References  JavaScript Books