Table of Contents | Previous | Next | Index


Chapter 11
Using Navigator Objects

This chapter describes JavaScript objects in Navigator and explains how to use them. These client-side JavaScript objects are sometimes referred to as Navigator objects, to distinguish them from server-side objects or user-defined objects.

This chapter contains the following sections:


Navigator Object Hierarchy

When you load a document in Navigator, it creates a number of JavaScript objects with property values based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself. The following figure illustrates this object hierarchy.

Figure 11.1   Navigator object hierarchy

In this hierarchy, an object's "descendants" are properties of the object. For example, a form named form1 is an object as well as a property of document, and is referred to as document.form1.

For a list of all objects and their properties, methods, and event handlers, see the Client-Side JavaScript Reference.

Every page has the following objects:

Depending on its content, the document may contain other objects. For instance, each form (defined by a FORM tag) in the document has a corresponding Form object.

To refer to specific properties, you must specify the object name and all its ancestors. Generally, an object gets its name from the NAME attribute of the corresponding HTML tag. For more information and examples, see Chapter 12, "Using Windows and Frames."

For example, the following code refers to the value property of a text field named text1 in a form named myform in the current document:

document.myform.text1.value
If an object is on a form, you must include the form name when referring to that object, even if the object does not need to be on a form. For example, images do not need to be on a form. The following code refers to an image that is on a form:

document.imageForm.aircraft.src='f15e.gif'
The following code refers to an image that is not on a form:

document.aircraft.src='f15e.gif'

Document Properties: an Example

The properties of the document object are largely content-dependent. That is, they are created based on the HTML in the document. For example, document has a property for each form and each anchor in the document.

Suppose you create a page named simple.html that contains the following HTML:

<HEAD><TITLE>A Simple Document</TITLE>
<SCRIPT>
function update(form) {
   alert("Form being updated")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="foo.cgi" METHOD="get" >Enter a value:
<INPUT TYPE="text" NAME="text1" VALUE="blahblah" SIZE=20 >
Check if you want:
<INPUT TYPE="checkbox" NAME="Check1" CHECKED    
   onClick="update(this.form)"> Option #1
<P>
<INPUT TYPE="button" NAME="button1" VALUE="Press Me"
   onClick="update(this.form)">
</FORM>
</BODY>
Given the preceding HTML example, the basic objects might have properties like those shown in the following table.

Table 11.1 Example object property values
Property Value
document.title
 "A Simple Document"
document.fgColor
 #000000
document.bgColor
 #ffffff
location.href
 "http://www.royalairways.com/samples/simple.html"
history.length
 7

Notice that the value of document.title reflects the value specified in the TITLE tag. The values for document.fgColor (the color of text) and document.bgColor (the background color) were not set in the HTML, so they are based on the default values specified in the Preferences dialog box (when the user chooses Preferences from the Navigator Edit menu).

Because the document has a form, there is also a Form object called myform (based on the form's NAME attribute) that has child objects for the checkbox and the button. Each of these objects has a name based on the NAME attribute of the HTML tag that defines it, as follows:

The Form object myform has other properties based on the attributes of the FORM tag, for example,

The Form object has child objects named button1 and text1, corresponding to the button and text fields in the form. These objects have their own properties based on their HTML attribute values, for example,

In practice, you refer to these properties using their full names, for example, document.myform.button1.value. This full name is based on the Navigator object hierarchy, starting with document, followed by the name of the form, myform, then the element name, button1, and, finally, the property name.


JavaScript Reflection and HTML Layout

JavaScript object property values are based on the content of your HTML document, sometimes referred to as reflection because the property values reflect the HTML. To understand JavaScript reflection, it is important to understand how the Navigator performs layout--the process by which Navigator transforms HTML tags into graphical display on your computer.

Generally, layout happens sequentially in the Navigator: the Navigator starts at the top of the HTML file and works downward, displaying output to the screen as it goes. Because of this "top-down" behavior, JavaScript reflects only HTML that it has encountered. For example, suppose you define a form with a couple of text-input elements:

<FORM NAME="statform">
<INPUT TYPE = "text" name = "userName" size = 20>
<INPUT TYPE = "text" name = "Age" size = 3>
These form elements are reflected as JavaScript objects that you can use after the form is defined: document.statform.userName and document.statform.Age. For example, you could display the value of these objects in a script after defining the form:

<SCRIPT>
document.write(document.statform.userName.value)
document.write(document.statform.Age.value)
</SCRIPT>
However, if you tried to do this before the form definition (above it in the HTML page), you would get an error, because the objects don't exist yet in the Navigator.

Likewise, once layout has occurred, setting a property value does not affect its value or appearance. For example, suppose you have a document title defined as follows:

<TITLE>My JavaScript Page</TITLE>
This is reflected in JavaScript as the value of document.title. Once the Navigator has displayed this in the title bar of the Navigator window, you cannot change the value in JavaScript. If you have the following script later in the page, it will not change the value of document.title, affect the appearance of the page, or generate an error.

document.title = "The New Improved JavaScript Page"
There are some important exceptions to this rule: you can update the value of form elements dynamically. For example, the following script defines a text field that initially displays the string "Starting Value." Each time you click the button, you add the text "...Updated!" to the value.

<FORM NAME="demoForm">
<INPUT TYPE="text" NAME="mytext" SIZE="40" VALUE="Starting Value">
<P><INPUT TYPE="button" VALUE="Click to Update Text Field"
   onClick="document.demoForm.mytext.value += '...Updated!' ">
</FORM>
This is a simple example of updating a form element after layout.

Using event handlers, you can also change a few other properties after layout has completed, such as document.bgColor.


Key Navigator Objects

This section describes some of the most useful Navigator objects: window, Frame, document, Form, location, history, and navigator. For more detailed information on these objects, see the Client-Side JavaScript Reference.

window and Frame Objects

The window object is the "parent" object for all other objects in Navigator. You can create multiple windows in a JavaScript application. A Frame object is defined by the FRAME tag in a FRAMESET document. Frame objects have the same properties and methods as window objects and differ only in the way they are displayed.

The window object has numerous useful methods, including the following:

window also has several properties you can set, such as location and status.

You can set location to redirect the client to another URL. For example, the following statement redirects the client to the Netscape home page, as if the user had clicked a hyperlink or otherwise loaded the URL:

location = "http://home.netscape.com"
You can use the status property to set the message in the status bar at the bottom of the client window; for more information, see "Using the Status Bar" on page 204.

For more information on windows and frames, see Chapter 12, "Using Windows and Frames." This book does not describe the full set of methods and properties of the window object. For the complete list, see the Client-Side JavaScript Reference.

document Object

Each page has one document object.

Because its write and writeln methods generate HTML, the document object is one of the most useful Navigator objects. For information on write and writeln, see "Using the write Method" on page 183.

The document object has a number of properties that reflect the colors of the background, text, and links in the page: bgColor, fgColor, linkColor, alinkColor, and vlinkColor. Other useful document properties include lastModified, the date the document was last modified, referrer, the previous URL the client visited, and URL, the URL of the document. The cookie property enables you to get and set cookie values; for more information, see "Using Cookies" on page 205.

The document object is the ancestor for all the Anchor, Applet, Area, Form, Image, Layer, Link, and Plugin objects in the page.

Users can print and save generated HTML by using the commands on the Navigator File menu (JavaScript 1.1 and later).

Form Object

Each form in a document creates a Form object. Because a document can contain more than one form, Form objects are stored in an array called forms. The first form (topmost in the page) is forms[0], the second forms[1], and so on. In addition to referring to each form by name, you can refer to the first form in a document as

document.forms[0]
Likewise, the elements in a form, such as text fields, radio buttons, and so on, are stored in an elements array. You could refer to the first element (regardless of what it is) in the first form as

document.forms[0].elements[0]
Each form element has a form property that is a reference to the element's parent form. This property is especially useful in event handlers, where you might need to refer to another element on the current form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
   onClick="this.form.text1.value=this.form.name">
</FORM>

location Object

The location object has properties based on the current URL. For example, the hostname property is the server and domain name of the server hosting the document.

The location object has two methods:

history Object

The history object contains a list of strings representing the URLs the client has visited. You can access the current, next, and previous history entries by using the history object's current, next, and previous properties. You can access the other history values using the history array. This array contains an entry for each history entry in source order; each array entry is a string containing a URL.

You can also redirect the client to any history entry by using the go method. For example, the following code loads the URL that is two entries back in the client's history list.

history.go(-2)
The following code reloads the current page:

history.go(0)
The history list is displayed in the Navigator Go menu.

navigator Object

The navigator object contains information about the version of Navigator in use. For example, the appName property specifies the name of the browser, and the appVersion property specifies version information for the Navigator.

The navigator object has three methods:


Navigator Object Arrays

Some Navigator objects have properties whose values are themselves arrays. These arrays are used to store information when you don't know ahead of time how many values there will be. The following table shows which properties of which objects have arrays as values.

Table 11.2 Predefined JavaScript arrays
Object Property Description
document
anchors

Reflects a document's <A> tags that contain a NAME attribute in source order

applets

Reflects a document's <APPLET> tags in source order

embeds

Reflects a document's <EMBED> tags in source order

forms

Reflects a document's <FORM> tags in source order

images

Reflects a document's <IMG> tags in source order (images created with the Image() constructor are not included in the images array)

layers

Reflects a document's <LAYER> and <ILAYER> tags in source order

links

Reflects a document's <AREA HREF="..."> tags, <A HREF=""> tags, and Link objects created with the link method in source order

Form
elements

Reflects a form's elements (such as Checkbox, Radio, and Text objects) in source order

Function
arguments

Reflects the arguments to a function

navigator
mimeTypes

Reflects all the MIME types supported by the client (either internally, via helper applications, or by plug-ins)

plugins

Reflects all the plug-ins installed on the client in source order

select
options

Reflects the options in a Select object (<OPTION> tags) in source order

window
frames

Reflects all the <FRAME> tags in a window containing a <FRAMESET> tag in source order

history

Reflects a window's history entries

You can index arrays by either their ordinal number or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.myForm.

For example, suppose the following form element is defined:

<INPUT TYPE="text" NAME="Comments">
If you need to refer to this form element by name, you can specify document.forms["Comments"].

All predefined JavaScript arrays have a length property that indicates the number of elements in the array. For example, to obtain the number of forms in a document, use its length property: document.forms.length.

JavaScript 1.0. You must index arrays by their ordinal number, for example document.forms[0].


Using the write Method

The write method of document displays output in the Navigator. "Big deal," you say, "HTML already does that." But in a script you can do all kinds of things you can't do with ordinary HTML. For example, you can display text conditionally or based on variable arguments. For these reasons, write is one of the most often-used JavaScript methods.

The write method takes any number of string arguments that can be string literals or variables. You can also use the string concatenation operator (+) to create one string from several when using write.

Consider the following script, which generates dynamic HTML with JavaScript:

<HEAD> 
<SCRIPT>
<!--- Hide script from old browsers
// This function displays a horizontal bar of specified width
function bar(widthPct) {
   document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>");
}
// This function displays a heading of specified level and some text
function output(headLevel, headText, text) {
   document.write("<H", headLevel, ">", headText, "</H",
      headLevel, "><P>", text)
}
// end script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
<!--- hide script from old browsers
bar(25)
output(2, "JavaScript Rules!", "Using JavaScript is easy...")
// end script hiding from old browsers -->
</SCRIPT>
<P> This is some standard HTML, unlike the above that is generated.
</BODY>

The HEAD of this document defines two functions:

The document BODY then calls the two functions to produce the display shown in the following figure.

Figure 11.2   Display created using JavaScript functions

The following line creates the output of the bar function:

document.write("<HR ALIGN='left' WIDTH=", widthPct, "%>")

Notice that the definition of bar uses single quotation marks inside double quotation marks. You must do this whenever you want to indicate a quoted string inside a string literal. Then the call to bar with an argument of 25 produces output equivalent to the following HTML:

<HR ALIGN="left" WIDTH=25%>

write has a companion method, writeln, which adds a newline sequence (a carriage return or a carriage return and linefeed, depending on the platform) at the end of its output. Because HTML generally ignores new lines, there is no difference between write and writeln except inside tags such as PRE, which respect carriage returns.

Printing Output

Navigator versions 3.0 and later print output created with JavaScript. To print output, the user chooses Print from the Navigator File menu. Navigator 2.0 does not print output created with JavaScript.

If you print a page that contains layers (Navigator 4.0 and later), each layer is printed separately on the same page. For example, if three layers overlap each other in the browser, the printed page shows each layers separately.

If you choose Page Source from the Navigator View menu or View Frame Source from the right-click menu, the web browser displays the content of the HTML file with the generated HTML. If you instead want to view the HTML source showing the scripts which generate HTML (with the document.write and document.writeln methods), do not use the Page Source and View Frame Source menu items. In this situation, use the view-source: protocol. For example, assume the file file://c|/test.html contains this text:

<HTML>
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>

If you load this URL into the web browser, it displays the following:

Hello, there.

If you choose Page Source from the View menu, the browser displays the following:

<HTML>
<BODY>
Hello,
 there.
</BODY>
</HTML>

If you load view-source:file://c|/test.html, the browser displays the following:

<HTML>
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>

Displaying Output

JavaScript in Navigator generates its results from the top of the page down. Once text has been displayed, you cannot change it without reloading the page. In general, you cannot update part of a page without updating the entire page. However, you can update the following:


Table of Contents | Previous | Next | Index

Last Updated: 05/27/99 21:21:36

Copyright (c) 1999 Netscape Communications Corporation

Any sample code included above is provided for your use on an "AS IS" basis, under the Netscape License Agreement - Terms of Use