JavaScript Dynamic Document Creation in New Windows

By HTMLGoodies Staff

Opening a New Window

Opening a new browser window is a simple process - superficially. To open a new browser window we use the open method of an existing window object. The open method allows us a great deal of control over the appearance of the window that we open, but a full explanation of the open method would take a whole article by itself.

This code demonstrates the simplest way of creating a new browser instance.

<HTML>
<HEAD>
<TITLE>New Browser Window</TITLE>
<SCRIPT>
window.open();
</SCRIPT>
</HEAD>
</HTML>

Just run this code in a browser and another browser window will open. As with all programming, we desire greater control than this. The window opens in a random position, with no title and no URL.

This new window has no further functionality. It is an equivalent of opening a blank document into a normal browser - there is nothing displayed and no interaction can occur.

But before we add content, the first thing we should do is to learn how to close the recently opened window. The computer usually handles closing windows and documents, and so when we deliberately interfere with this process, we need to supply the routines that maintain expected operations. If we don't close a window, the window will cause havoc later on. Fortunately for us, this is not a very difficult task.

Closing a New Window

In order to be able to close a window, when we open it we have to store the value returned by the open method in a variable. This variable then holds a unique reference to the newly opened window, and we use this reference to close the window again. If we don't do this, we have no access to the newly opened window.

This code demonstrates assigning a variable the return value of the open method, and then using this variable to close the window. You have to be alert during the running of the code, the program opens and closes the window fairly quickly. Normally, we would place code between these two statements, but this program is only an example.

<HTML>
<HEAD>
<TITLE>Opened and Closed Window</TITLE>
<SCRIPT>
newwindow=window.open();
newwindow.close();
</SCRIPT>
</HEAD>
</HTML>

So now we can open and close windows, but our new windows do not have much variety, and we are stuck with the simple window that opens.

We could add content by now, but before we do, we will examine opening a larger variety of browser windows. Still using the simple open method, we can use a much more complex version of the same function. The parameter-less version merely creates a default window. There are several parameters of the open method that allow us to vary the features of the new window. We can supply the parameters with our own values to create windows of our choice.

window.open Parameters

The open method has four main parameters, of which one, features, contains even more parameters. These parameters define the visual appearance and behavior of the new browser window.

Syntax:

window.open(url,target,features,replace)

As we shall only be looking at url and a few of the features, I shall tell you here that target defines a destination window and replace allows you to overwrite any current history entry for a page. A full discussion of these would be another article in itself.

features controls several aspects, including the position and size of the new browser and presence of toolbars on the new browser.

Continuing the simple style of creating windows, we shall look at a window which uses the url parameter.

url

The url parameter allows us to define a URL for the new window. This means that when a new browser is created, instead of displaying a blank page, it displays the document that is at the URL passed to the open function. Although this defeats the point of any DDC, it is an important extension to the open function, and the URL may point to a document with DDC.

As most of the examples in these two articles have been quite abstract, and we need a URL for further examples, I have written a new HTML program, which can be used as the destination for a general URL.

Save this code in an appropriate directory with an appropriate filename, for example dummy.htm. The program dummy file displays two lines of text, one with red text on a blue background, and the other with green text on a yellow background.

<HTML>
<HEAD>
<TITLE>Dummy file</TITLE>
</HEAD>
<BODY>
<P STYLE="color:red;background-color:blue">Red on Blue</P>
<P STYLE="color:green;background-color:yellow">Green on Yellow</P>
</BODY>
</HTML>

We are examining the url parameter of the open method, and we assign our dummy.htm file to the url parameter. So, for example:

<HTML>
<HEAD>
<TITLE>New Dummy Window</TITLE>
<SCRIPT>
window.open(url='dummy.htm');
</SCRIPT>
</HEAD>
</HTML>

This code opens the dummy.htm file in a new window. We can drop the actual url= part, and just use:

<HTML>
<HEAD>
<TITLE>New Dummy Window 2</TITLE>
<SCRIPT>
window.open('dummy.htm');
</SCRIPT>
</HEAD>
</HTML>

Obviously, we can also place more impressive URL's in the parameter - try one, and don't forget to add the http:// part if you are traveling off-site.

<HTML>
<HEAD>
<TITLE>New URL Window</TITLE>
<SCRIPT>
window.open('http://www.webdevelopersjournal.com');
</SCRIPT>
</HEAD>
</HTML>

This will open the Web Developer's Journal web site in a new window, still keeping the original window open and intact. This currently has several irritating qualities, our original window has no content to preserve, and the new browser window is the wrong size. Both of these issues of resolved in the remainder of this article, and as we are still examining the open function, we shall first look at changing the position and size of any new browser.

The remaining open function parameters involve quite complex concepts, and can cause a lot of headaches unless you understand exactly what you are doing. It is also important to note that the parameters are ordered, the url parameter is the first parameter, an that this is an unchangeable fact. This is very important when we are using a more complete version of the open method, we want to be sure that we are assigned the correct values to their intended parameters, otherwise the new window will not resemble the intended appearance.

The final development of new windows examines exact positioning and sizing of the new window. This is done using the parameters top and left for position, and height and width for size. These parameters are sub-parameters of the features parameter.

Position and Size

When we open a new browser, we can set the position and size. The position is defined by the absolute screen co-ordinates, and measured from the top and left, hence the parameters names. We can also set the size, i.e. the width and height in pixels.

The unmentioned features are set to their default values. Unless we explicitly mention them, this fact will not change.

This code demonstrates opening a new browser at a certain position and with a certain size. To see an example of how changing these parameters changes the new browser, try varying the values in this example.

<HTML>
<HEAD>
<TITLE>New Sized Windows</TITLE>
<SCRIPT>
window.open('dummy.htm','','left=10,top=10,width=200,height=200');
</SCRIPT>
</HEAD>
</HTML>

There are two important things to notice about the window.open line of code. The first is the inclusion of the empty string for the target parameter, and the second is that the list of features is all one string. If you leave the empty string out, the list of features parameter is read as the target parameter, which is garbage to the computer. The features parameter itself is one long, comma-separated list of individual properties of the browser.

This program creates a new square browser window, with a top-left co-ordinate of (10,10), and sides of length 200.

To keep in the theme of Dynamic Document Creation, we wish to add dynamic document creation capability to the new windows.

As we discussed in my last article, DDC involves using the document method write, and its power is in its ability to write text, variables and HTML to a document. Another of the powers of DDC is the power we have to dynamically write across windows, i.e. write to a different window from the one we are currently in. This sub-topic I have called Cross-Window Writing as this describes the effective action of the DDC concept.
Cross-Window Write

This is Javascript for IE5. See our policy on browser-specific JavaScript.

Cross-Window writing involves writing to a new window from an existing one. Essentially, the techniques involved are the same as with writing to the same document, but we have several extra freedoms.

One of these extra freedoms comes from the fact that the new window is also a new document. This means that we can write to it and not destroy the document content of the previously existing window, which gives us even more control over web pages. We can now report on our web page without having to constantly refresh the web page, use frames, or use DHTML.

To use this power, we must create a new window and store a reference to it in a variable, as we did when we learned how to close a window. We use this variable as a document, and because the variable is a document it will accept the write method. This program demonstrates a very simple Cross-Window DDC.

<HTML>
<HEAD>
<TITLE>Cross-Window Write</TITLE>
<SCRIPT>
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write('Hello World.');
newdocument.close();
</SCRIPT>
</HEAD>
</HTML>

This program involves quite a jump in program size, but has released the power of write on our new window. The program uses basic DOM theory, which says that every window contains a document. We access newwindow.document and store this document in the newdocument variable. As this variable corresponds to the newwindow document, any write method used on newdocument shows up in the newwindow window.

As we have interrupted the usual flow of the operating system, we must close the document ourselves. If we didn't close the document, the computer would still be waiting for more HTML, and indeed would parse the next input as HTML, which would generally produce an error.

Note that there is no need to close the window yet, we may still need it, and this raises the important point that the window is not the document.

Once we have written across the document, we can introduce some of the DDC ideas that we discussed in my first article, such as writing variables and writing HTML.

Cross-Writing Variables

Another of the freedoms a new window gives us, although more of a liberty, is the ability we now have to pass variables from one window to another. This is most useful when we want to tailor a new window to user preferences based on results of a selection process, or if we wish to report a variable to a user, but generally this technique has many uses.

With a few adjustments to the previous DDC HTML web page, we can begin passing variables to a new window. This program takes the text from a text box and displays it in a new window.

<HTML>
<HEAD>
<TITLE>Cross-Window Variable Write</TITLE>
<SCRIPT>
function newname() {
message='Hello '+word.value;
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write(message);
newdocument.close();
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT TYPE="TEXT" NAME="word" onclick="newname();">Click when ready
</BODY>
</HTML>

Enter some text in the text box, and then click it. The text can be read using DHTML techniques on the DOM, effectively by reading word.value. This value is extended into the message string, and this string it written to the new window. Magic!

Another use of the write method is to write HTML to a document. This HTML is then parsed by the browser and treated as a normal document. We can combine this technique with the ability we have to transfer variables as well.

Cross-Window HTML

Writing DDC HTML has a lot of uses. We can quickly and readily create documents that are chosen by the viewer. We can offer constantly new web pages to display products. Instead of having to write code for 100 works of art, we can use DDC and pass the image file name as a variable. Zero files versus 100!

The basic essence of writing DDC HTML is the same as just using write. We are clever about it though, and choose the string that we write to be an HTML document. The new window receives some HTML, and then attempts to parse it into a visible document. We can also intersperse variables inside our HTML string to create a unique web page.

This code offers the viewer several display options for the new window that will open when the button is pressed. The document that is created elaborates the text from the text box, and displays it in the foreground color, against the background color.

<HTML>
<HEAD>
<TITLE>Cross-Window HTML</TITLE>
<SCRIPT>
function newHTML() {
for (i=0;i<3;i++) {
cc=mainform.forecolor[i];
if (cc.checked) newfcolor=cc.value;
cc=mainform.backcolor[i];
if (cc.checked) newbcolor=cc.value;
}
HTMLstring='<HTML>\n';
HTMLstring+='<HEAD>\n';
HTMLstring+='<TITLE>New Document</TITLE>\n';
HTMLstring+='</HEAD>\n';
HTMLstring+='<BODY bgColor="'+newbcolor+'">\n';
HTMLstring+='<P Style="color:'+newfcolor+'">Hello '+mainform.word.value+'</P>\n';
HTMLstring+='</BODY>\n';
HTMLstring+='</HTML>';
alert(HTMLstring);
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write(HTMLstring);
newdocument.close();
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="mainform">
<INPUT TYPE="TEXT" NAME="word">Enter your name here
<BR>
<U>Foreground Color</U>
<INPUT TYPE="RADIO" NAME="forecolor" VALUE="red" CHECKED>Red
<INPUT TYPE="RADIO" NAME="forecolor" VALUE="green">Green
<INPUT TYPE="RADIO" NAME="forecolor" VALUE="blue">Blue
<BR><U>Background Color</U>
<INPUT TYPE="RADIO" NAME="backcolor" VALUE="black" CHECKED>Black
<INPUT TYPE="RADIO" NAME="backcolor" VALUE="white">White
<INPUT TYPE="RADIO" NAME="backcolor" VALUE="yellow">Yellow
<BR>
<INPUT TYPE="BUTTON" VALUE="New Window" onclick="newHTML();">
</FORM>
</BODY>
</HTML>

Although this program is a lot larger than programs we have examined before, it is only 'bulkier', i.e. it has a larger <SCRIPT> section and a larger <BODY> section than normal, but is not particularly any more complex than a smaller HTML document.

If we examine the <BODY> element first, we see that there is only a form with a text box for input, and two radio groups, one that defines the foreground color, and the other defining the background color. The viewer can alter these colors. The program detects the color selection and provides a new window which takes these color values into account.

All the elements are named, and we do not use a normal SUBMIT button, as this doesn't work particularly well for such a short range procedure. In this case, the BUTTON calls the function newHTML().

newHTML(), which is defined in the <SCRIPT> element, does all the work. The first thing it does is set the two color variables, newfcolor and newbcolor (new foreground color and new background color) according to the radio selections. This is done by cycling through all the radio buttons, asking each if it is checked or not, and then using the value of the checked radio button as the color value. As only one radio button in a group can ever be checked, and the values of the individual radio buttons are carefully chosen, this technique always works.

Once we have our color variables, we construct an HTML document in the string variable HTMLstring. This string contains an entire HTML program, and the form variables are inserted into it.

If you add the line:

alert(HTMLstring);

after the final extension to HTMLstring, you can see what HTMLstring looks like before we send it to the new window,it looks exactly like a normal HTML document.

Once we have done this, we can write HTMLstring to a new document. As we are supplying HTML, this is then parsed and converted into the document the viewer requested.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •