Client-Side Scripting with JavaScript


Part 10 - Working with Windows

The window object is the primary browser object in JavaScript. A new window can be created with the open() method:

   windowName = window.open(URL, window name, features list)

   FEATURES:
     width=
     height= 
     toolbar=no/yes
     scrollbars=no/yes
     status=no/yes

An example of opening a document in a new window:

NewWin=window.open('chap1.html','NewWin','toolbar=no, status=no,scrollbars=yes,width=500,height=300') <A HREF="javascript:NewWin=window.open('chap1.html','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=500,height=300'); NewWin.focus(); return true;">Open new window.</A>
The NewWin.focus() command refers to the window object and brings it to the front.


To open a new window, select this link.

Once you create a new window, you can control the display of the document with JavaScript commands:

NewWin.location.hash='Growth'; NewWin.focus(); NewWin.location='chap2.html'; NewWin.focus(); NewWin.close()

The location object can be used to specify a new URL to be displayed in the window. The location.hash property can be set to a specific location within the document.

Select this link to move to a specific part of the other window ("Growth of Computers in Society").
This link opens a new file in the other window.
To close the window, select this link.

Exercise 4

In addition to display an exisiting file, JavaScript commands can be used to create text in a new window. The URL in the window.open command would be null (""). Creating text in the window is done by placing the window name before the document.write command. In the example above, NewWin.document.write would place text in the new window.

The following fragment is set up to run a JavaScript function when the link is clicked. Complete the function to open a new window and write some text to that window. Note that the first thing you must write to the window is "<HTML><BODY>" to indicate an HTML document.

<HTML> <HEAD> <TITLE>Writing to a Window</TITLE> <SCRIPT LANGUAGE="JavaScript"> function OpenWin() { } </SCRIPT> </HEAD> <BODY> <H3>New Window</H3> This example writes text to a new window. <A HREF="javascript:OpenWin()">Click here</A> to start. </BODY> </HTML>

Here is one way to do it.

Next Next: Images