Java Script Notes Chapters 1-9
Java Script Notes Chapters 1-9
Introduction
This chapter briefly introduces JavaScript, Netscape's cross-platform, object-based scripting language
for client and server applications.
JavaScript lets you create applications that run over the Internet. Using JavaScript, you can create
dynamic HTML pages that process user input and maintain persistent data using special objects, files,
and relational databases. You can build applications ranging from internal corporate information
management and intranet publishing to mass-market electronic transactions and commerce. Through
JavaScript's LiveConnect functionality, your applications can access Java and CORBA distributed
object applications.
Server-side and client-side JavaScript share the same core language. This core language corresponds
to ECMA-262, the scripting language standardized by the European standards body, with some
additions. The core language contains a set of core objects, such as the Array and Date objects. It
also defines other language features such as its expressions, statements, and operators. Although
server-side and client-side JavaScript use the same core functionality, in some cases they use them
differently..
Client-side JavaScript (or Navigator JavaScript) encompasses the core language plus extras such as
the predefined objects only relevant to running JavaScript in a browser. Server-side JavaScript
encompasses the same core language plus extras such as the predefined objects and functions only
relevant to running JavaScript on a server.
Client-side JavaScript is embedded directly in HTML pages and is interpreted by the browser
completely at runtime. Because production applications frequently have greater performance
demands upon them, JavaScript applications that take advantage of its server-side capabilities are
compiled before they are deployed. The next two sections introduce you to how JavaScript works on
the client and on the server.
Page No:1
Client-Side JavaScript
Web browsers such as Netscape Navigator 2.0 (and later versions) can interpret client-side JavaScript
statements embedded in an HTML page. When the browser (or client) requests such a page, the
server sends the full content of the document, including HTML and JavaScript statements, over the
network to the client. The client reads the page from top to bottom, displaying the results of the
HTML and executing JavaScript statements as it goes. This process produces the results that the user
sees and is illustrated in Figure 1.2.
Client-side JavaScript statements embedded in an HTML page can 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, the embedded JavaScript on the HTML page can check the
entered data and display a dialog box to the user who enters invalid data.
Server-Side JavaScript
On the server, JavaScript is also embedded in HTML pages. The server-side statements can connect
to relational databases from different vendors, share information across users of an application,
access the file system on the server, or communicate with other applications through LiveConnect
and Java. A compiled JavaScript application can also include client-side JavaScript in addition to
server-side JavaScript.
In contrast to pure client-side JavaScript scripts, JavaScript applications that use server-side
JavaScript are compiled into bytecode executable files. These application executables are run in
concert with a web server that contains the JavaScript runtime engine. For this reason, creating
JavaScript applications is a two-stage process.
In the first stage, shown in Figure 1.3, you (the developer) create HTML pages (which can contain
both client-side and server-side JavaScript statements) and JavaScript files. You then compile all of
those files into a single executable.
Page No:2
Figure 1.3 Server-side JavaScript during development.
In the second stage, shown in Figure 1.4, a page in the application is requested by a client browser.
The runtime engine uses the application executable to look up the source page and dynamically
generate the HTML page to return. It runs any server-side JavaScript statements found on the page.
The result of those statements might add new HTML or client-side JavaScript statements to the
HTML page. It then sends the resulting page over the network to the Navigator client, which displays
the results.
Page No:3
In contrast to standard Common Gateway Interface (CGI) programs, all JavaScript is integrated
directly into HTML pages, facilitating rapid development and easy maintenance. JavaScript's Session
Management Service contains objects you can use to maintain data that persists across client requests,
multiple clients, and multiple applications. JavaScript's LiveWire Database Service provides objects
for database access that serve as an interface to Structured Query Language (SQL) database servers.
JavaScript Objects
JavaScript has predefined objects for the core language, as well as additions for client-side and
server-side JavaScript.
Anchor, Applet, Area, Button, Checkbox, document, event, FileUpload, Form, Frame, Hidden,
History, Image, Layer, Link, Location, MimeType, navigator, Option, Password, Plugin, Radio,
Reset, screen, Select, Submit, Text, Textarea, Window
These objects represent information relevant to working with JavaScript in a web browser. Many of
these objects are related to each other by occurring as property values. For example, to access the
images in a document, you use the [Link] array, each of whose elements is a Image
object. Figure 1.5 shows the client-side object containment hierarchy.
blob, client, Connection, Cursor, database, DbPool, File, Lock, project, request, Resultset,
SendMail, server, Stproc
Page No:4
As shown in Figure 1.6, some of the additional server-side objects also have a containment hierarchy.
JavaScript Security
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.
JavaScript for Navigator 3.0 has a feature called data tainting that retains the security restriction but
provides a means of secure access to specific components on a page.
When data tainting is enabled, JavaScript in one window can see properties of another
window, no matter what server the other window's document was loaded from. However, the
author of the other window taints (marks) property values or other data that should be secure
or private, and JavaScript cannot pass these tainted values on to any server without the user's
permission.
When data tainting is disabled, a script cannot access any properties of a window on another
server.
In Navigator 4.0, data tainting has been removed. Instead, Navigator 4.0 provides signed JavaScript
scripts for more reliable and more flexible security.
Page No:5
Chapter 2
Operators
JavaScript has assignment, comparison, arithmetic, bitwise, logical, string, and special operators.
This chapter describes the operators and contains information about operator precedence.
Page No:6
Assignment = Assigns the value of the second operand to the first operand.
Operators
+= Adds 2 numbers and assigns the result to the first.
-= Subtracts 2 numbers and assigns the result to the first.
*= Multiplies 2 numbers and assigns the result to the first.
/= Divides 2 numbers and assigns the result to the first.
%= Computes the modulus of 2 numbers and assigns the result to the first.
&= Performs a bitwise AND and assigns the result to the first operand.
^= Performs a bitwise XOR and assigns the result to the first operand.
|= Performs a bitwise OR and assigns the result to the first operand.
<<= Performs a left shift and assigns the result to the first operand.
>>= Performs a sign-propagating right shift and assigns the result to the
first operand.
>>>= Performs a zero-fill right shift and assigns the result to the first
operand.
Comparison == Returns true if the operands are equal.
Operators
!= Returns true if the operands are not equal.
> Returns true if left operand is greater than right operand.
>= Returns true if left operand is greater than or equal to right operand.
< Returns true if left operand is less than right operand.
<= Returns true if left operand is less than or equal to right operand.
Special ?: Lets you perform a simple "if...then...else"
Operators
, Evaluates two expressions and returns the result of the second
expression.
delete Lets you delete an object property or an element at a specified index
in an array.
new Lets you create an instance of a user-defined object type or of one of
the built-in object types.
this Keyword that you can use to refer to the current object.
typeof Returns a string indicating the type of the unevaluated operand.
void The void operator specifies an expression to be evaluated without
returning a value.
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 assignment operators are shorthand for
standard operations, as shown in Table 2.2.
Page No:7
Shorthand operator Meaning
x += y x = x + y
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y
x %= y x = x % y
x <<= y x = x << y
x >>= y x = x >> y
x >>>= y x = x >>> y
x &= y x = x & y
x ^= y x = x ^ y
x |= y x = x | y
Comparison Operators
A comparison operator compares its operands and returns a logical value based on whether the
comparison is true or not. The operands can be numerical or string values. When used on string
values, the comparisons are based on the standard lexicographical ordering.
They are described in Table 2.3. In the examples in this table, assume var1 has been assigned the
value 3 and var2 had been assigned the value 4.
Not equal (!=) Returns true if the operands are not equal. var1 != 4
Greater than (>) Returns true if left operand is greater than right var2 > var1
operand.
Greater than or equal Returns true if left operand is greater than or equal var2 >= var1
var1 >= 3
(>=) to right operand.
Less than (<) Returns true if left operand is less than right var1 < var2
operand.
Less than or equal Returns true if left operand is less than or equal to var1 <= var2
var2 <= 5
(<=) right operand.
Arithmetic Operators
Arithmetic operators take numerical values (either literals or variables) as their operands and return a
single numerical value. The standard arithmetic operators are addition (+), subtraction (-),
multiplication (*), and division (/). These operators work as they do in other programming languages.
Page No:8
% (Modulus)
++ (Increment)
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 three, then the statement y = x++ sets y to 3 and increments x to 4. If x is 3, then
the statement y = ++x increments x to 4 and sets y to 4.
-- (Decrement)
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 three, then the statement y = x-- sets y to 3 and decrements x to 2. If x is 3, then
the statement y = --x decrements x to 2 and sets y to 2.
- (Unary Negation)
The unary negation operator precedes its operand and negates it. For example, y = -x negates the
value of x and assigns that to y; that is, if x were 3, y would get the value -3 and x would retain the
value 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 nine has a binary representation of
1001. Bitwise operators perform their operations on such binary representations, but they return
standard JavaScript numerical values.
Page No:9
Bitwise XOR a ^ b Returns a one in a bit position if bits of one but not both operands
are one.
Bitwise NOT ~ a Flips the bits of its operand.
Left shift a << b Shifts a in binary representation b bits to left, shifting in zeros from
the right.
Sign-propagating a >> b Shifts a in binary representation b bits to right, discarding bits
right shift shifted off.
Zero-fill right shift a >>> Shifts a in binary representation b bits to the right, discarding bits
b
shifted off, and shifting in zeros from the left.
The operands are converted to thirty-two-bit integers and expressed by 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.
For example, the binary representation of nine is 1001, and the binary representation of fifteen is
1111. So, when the bitwise operators are applied to these values, the results are as follows:
The bitwise 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 thirty-two-bit integers and return a result of the same type as
the left operator.
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 thirty-six, because 1001 shifted two bits to the left becomes 100100, which
is thirty-six.
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 two, because 1001 shifted two bits to the right becomes 10, which is two.
Likewise, -9>>2 yields -3, because the sign is preserved.
This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off
to the right are discarded. Zero bits are shifted in from the left.
Page No:10
For example, 19>>>2 yields four, because 10011 shifted two bits to the right becomes 100, which is
four. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same
result.
Logical Operators
Logical operators take Boolean (logical) values as operands and return a Boolean value.
Examples
Short-Circuit Evaluation
As logical expressions are evaluated left to right, they are tested for possible "short-circuit"
evaluation using the following rules:
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of
the above expressions is not evaluated, so any side effects of doing so do not take effect.
String Operators
Page No:11
In addition to the comparison operators, which can 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 has the value "alpha," then the expression mystring += "bet" evaluates to
"alphabet" and assigns this value to mystring.
Special Operators
?: (Conditional operator)
The conditional operator is the only JavaScript operator that takes three operands. This operator is
frequently used as a shortcut for the if statement.
Syntax
Parameters
Description
If condition is true, the operator returns the value of expr1; otherwise, it returns the value of
expr2. For example, to display a different message based on the value of the isMember variable, you
could use this statement:
[Link] ("The fee is " + (isMember ? "$2.00" : "$10.00"))
, (Comma operator)
The comma operator is very simple. It evaluates both of its operands and returns the value of the
second operand.
Syntax
expr1, expr2
Parameters
Description
You can use the comma operator when you want to include multiple expressions in a location that
requires a single expression. The most common usage of this operator is to supply multiple
parameters in a for loop.
For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the
comma operator to increment two variables at once. The code prints the values of the diagonal
elements in the array:
delete
Page No:12
Deletes an object's property or an element at a specified index in an array.
Syntax
delete [Link]
delete objectName[index]
delete property
Parameters
Description
If the deletion succeeds, the delete operator sets the property or element to undefined. delete
always returns undefined.
new
An operator that lets you create an instance of a user-defined object type or of one of the built-in
object types that has a constructor function.
Syntax
Arguments
Description
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
[Link] = "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.
You can add a property to a previously defined object type by using the [Link]
property. This defines a property that is shared by all objects created with that function, rather than by
just one instance of the object type. The following code adds a color property to all objects of type
car, and then assigns a value to the color property of the object car1. For more information, see
prototype
Page No:13
[Link]=null
[Link]="black"
[Link]="The day you were born"
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,
and year. To do this, you would write the following function:
function car(make, model, year) {
[Link] = make
[Link] = model
[Link] = 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
[Link] is the string "Eagle", [Link] is the integer 1993, and so on.
You can create any number of car objects by calls to new. For example,
this
A keyword that you can use to refer to the current object. In general, in a method this refers to the
calling object.
Syntax
this[.propertyName]
Examples
Suppose a function called validate validates an object's value property, given the object and the
high and low values:
Page No:14
function validate(obj, lowval, hival) {
if (([Link] < lowval) || ([Link] > 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)">
typeof
void
You can 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.
Page No:15
<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([Link]())">
Click here to submit</A>
Chapter 3
Statements
This chapter describes all JavaScript 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 semicolon.
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}
Page No:16
indicates a block of statements, which can consist of a single statement or multiple statements
delimited by a curly braces { }.
break Statement that terminates the current while or for loop and transfers program control
to the statement following the terminated loop.
comment Notations by the author to explain what a script does. Comments are ignored by the
interpreter.
continue 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.
delete Deletes an object's property or an element of an array.
do...while Executes its statements until the test condition evaluates to false. Statement is
executed at least once.
export Allows a signed script to provide properties, functions, and objects to other signed or
unsigned scripts.
for 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.
for...in Statement that iterates a specified variable over all the properties of an object. For
each distinct property, JavaScript executes the specified statements.
function Statement that declares a JavaScript function name with the specified parameters.
Acceptable parameters include strings, numbers, and objects.
if...else 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.
import Allows a script to import properties, functions, and objects from a signed script
which has exported the information.
labeled Provides an identifier that can be used with break or continue to indicate where the
program should continue execution.
return Statement that specifies the value to be returned by a function.
switch Allows a program to evaluate an expression and attempt to match the expression's
value to a case label.
var Statement that declares a variable, optionally initializing it to a value.
while Statement that creates a loop that evaluates an expression, and if it is true, executes a
block of statements.
with Statement that establishes the default object for a set of statements.
break
Terminates the current while or for loop and transfers program control to the statement following
the terminated loop.
Syntax
Page No:17
break
break label
Argument
Description
The break statement can now include an optional label that allows the program to break out of a
labeled statement. This type of break must be in a statement identified by the label used by break.
Examples
The following function has a break statement that terminates the while loop when e 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
}
In the following example, a statement labeled checkiandj contains a statement labeled checkj. If
break is encountered, the program breaks out of the checkj statement and continues with the
remainder of the checkiandj statement. If break had a label of checkiandj, the program would
break out of the checkiandj statement and continue at the statement following checkiandj.
checkiandj :
if (4==i) {
[Link]("You've entered " + i + ".<BR>");
checkj :
if (2==j) {
[Link]("You've entered " + j + ".<BR>");
break checkj;
[Link]("The sum is " + (i+j) + ".<BR>");
}
[Link](i + "-" + j + "=" + (i-j) + ".<BR>");
}
comment
Notations by the author to explain what a script does. Comments are ignored by the interpreter.
Syntax
// comment text
/* multiple line comment text */
Description
Examples
Page No:18
// 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. */
delete
Deletes an object's property or an element at a specified index in an array.
Syntax
delete [Link]
delete objectName[index]
delete property
Arguments
Description
If the delete operator succeeds, it sets the property of element to undefined; the operator always
returns undefined.
You can only use the delete operator to delete object properties and array entries. You cannot use
this operator to delete objects or variables. Consequently, you can only use the third form within a
with statement, to delete a property from the object.
do...while
Executes its statements until the test condition evaluates to false. Statement is executed at least once.
Syntax
do
statement
while (condition);
Arguments
statement Block of statements that is executed at least once and is re-executed each time the
condition evaluates to true.
condition Evaluated after each pass through the loop. If condition evaluates to true, the
statements in the preceding block are re-executed. When condition evaluates to false,
control passes to the statement following do while.
Example
In the following example, the do loop iterates at least once and reiterates until i is no longer less than
5.
do {
i+=1
[Link](i);
while (i<5);
Page No:19
export
Allows a signed script to provide properties, functions, and objects to other signed or unsigned
scripts.
Syntax
Parameters
Description
Typically, information in a signed script is available only to scripts signed by the same principals. By
exporting properties, functions, or objects, a signed script makes this information available to any
script (signed or unsigned). The receiving script uses the companion import statement to access the
information.
for
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
Arguments
Examples
The following for statement starts by declaring the variable i and initializing it to 0. It checks that i
is less than nine, performs the two succeeding statements, and increments i by 1 after each pass
through the loop.
for (var i = 0; i < 9; i++) {
n += i
myfunc(n)
}
for...in
Page No:20
Iterates a specified variable over all the properties of an object. For each distinct property, JavaScript
executes the specified statements.
Syntax
Arguments
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, objName) {
var result = ""
for (var i in obj) {
result += objName + "." + i + " = " + obj[i] + "<BR>"
}
result += "<HR>"
return result
}
function
Declares a JavaScript function with the specified parameters. Acceptable parameters include strings,
numbers, and objects.
Syntax
Arguments
Description
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.
In addition to defining functions as described here, you can also define Function objects.
Examples
Page No:21
if...else
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}]
Arguments
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 Can be any JavaScript statements, including further nested if statements.
statements2
Multiple statements must be enclosed in braces.
Examples
if (cipher_char == from_char) {
result = result + to_char
x++}
else
result = result + clear_char
import
Allows a script to import properties, functions, and objects from a signed script which has exported
the information.
Syntax
Parameters
nameN List of properties, functions, and objects to import from the export file.
objectName Name of the object that will receive the imported names.
* imports all properties, functions, and objects from the export script.
Description
The objectName parameter is the name of the object that will receive the imported names. For
example, if f and p have been exported, and if obj is an object from the importing script, then
import obj.f, obj.p
makes f and p accessible in the importing script as properties of obj.
Typically, information in a signed script is available only to scripts signed by the same principals. By
exporting (using the export statement) properties, functions, or objects, a signed script makes this
information available to any script (signed or unsigned). The receiving script uses the import
statement to access the information.
Page No:22
The script must load the export script into a window, frame, or layer before it can import and use any
exported properties, functions, and objects.
labeled
Provides an identifier that can be used with break or continue to indicate where the program should
continue execution.
In a labeled statement, break or continue must be followed with a label, and the label must be the
identifier of the labeled statement containing break or continue.
Syntax
label :
statement
Arguments
statement Block of statements. break can be used with any labeled statement, and continue can be
used with looping labeled statements.
Example
For an example of a labeled statement using break, see break. For an example of a labeled statement
using continue, see continue.
return
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
}
switch
Allows a program to evaluate an expression and attempt to match the expression's value to a case
label.
Syntax
switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
Page No:23
default : statement;
}
Arguments
Description
The program first looks for a label matching the value of expression and then executes the associated
statement. If no matching label is found, the program looks for the optional default statement, and if
found, executes the associated statement. If no default statement is found, the program continues
execution at the statement following the end of switch.
The optional break statement associated with each case label ensures that the program breaks out of
switch once the matched statement is executed and continues execution at the statement following
switch. If break is omitted, the program continues execution at the next statement in the switch
statement.
Example
In the following example, if expression evaluates to "Bananas," the program matches the value with
case "Bananas" and executes the associated statement. When break is encountered, the program
breaks out of switch and executes the statement following switch. If break were omitted, the
statement for case "Cherries" would also be executed.
switch (i) {
case "Oranges" :
[Link]("Oranges are $0.59 a pound.<BR>");
break;
case "Apples" :
[Link]("Apples are $0.32 a pound.<BR>");
break;
case "Bananas" :
[Link]("Bananas are $0.48 a pound.<BR>");
break;
case "Cherries" :
[Link]("Cherries are $3.00 a pound.<BR>");
break;
default :
[Link]("Sorry, we are out of " + i + ".<BR>");
}
[Link]("Is there anything else you'd like?<BR>");
var
Declares a variable, optionally initializing it to a value.
Syntax
Arguments
Description
Page No:24
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.
Examples
while
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
}
Arguments
condition 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 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 statement.
Examples
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.
with
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.
Syntax
with (object){
statements
}
Page No:25
Arguments
object Specifies the default object to use for the statements. The parentheses around object are
required.
statements 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
with (Math) {
a = PI * r * r
x = r * cos(PI)
y = r * sin(PI/2)
}
Chapter 4
Core
This chapter includes the JavaScript core objects Array, Boolean, Date, Function, Math, Number,
Object, and String. These objects are used in both client-side and server-side JavaScript.
Object Description
Array Represents an array.
Boolean Represents a Boolean value.
Date Represents a date.
Function Specifies a string of JavaScript code to be compiled as a function.
Math Provides basic math constants and functions; for example, its PI property contains the
value of pi.
Number Represents primitive numeric values.
Object Contains the base functionality shared by all JavaScript objects.
RegExp Represents a regular expression; also contains static properties that are shared among
Page No:26
all regular expression objects.
String Represents a JavaScript string.
Array
Represents an array of elements.
Core object
Created by
Parameters
arrayLength (Optional) The initial length of the array. You can access this value using the length
property.
elementN (Optional) A list of values for the array's elements. When this form is specified, the
array is initialized with the specified values as its elements, and the array's length
property is set to the number of arguments.
Description
In Navigator 3.0, you can specify an initial length when you create the array. The following code
creates an array of five elements:
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"
However, in Navigator 4.0, if you specify LANGUAGE="JavaScript1.2" in the <SCRIPT> tag, using
new Array(1) creates a new array with a[0]=1.
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 0, then assigns a value to element 99. This
changes the length of the array to 100.
In Navigator 4.0, the result of a match between a regular expression and a string can create an array.
This array has properties and elements that provide information about the match. An array is the
return value of [Link], [Link], and [Link]. To help explain these properties
and elements, look at the following example and then refer to the table below:
<SCRIPT LANGUAGE="JavaScript1.2">
//Match one d followed by one or more b's followed by one d
Page No:27
//Remember matched b's and the following d
//Ignore case
myRe=/d(b+)(d)/i;
myArray = [Link]("cdbBdbsbz");
</SCRIPT>
The properties and elements returned from this match are as follows:
Property/Element Description Example
input A read-only property that reflects the original string against which cdbBdbsbz
the regular expression was matched.
index A read-only property that is the zero-based index of the match in the 1
string.
[0] A read-only element that specifies the last matched characters. dbBd
[1], ...[n] Read-only elements that specify the parenthesized substring matches, [1]=bB
if included in the regular expression. The number of possible [2]=d
parenthesized substrings is unlimited.
Property Summary
index For an array created by a regular expression match, the zero-based index of the match in
the string.
input For an array created by a regular expression match, reflects the original string against
which the regular expression was matched.
length Reflects the number of elements in an array
prototype Allows the addition of properties to an Array object.
Method Summary
Examples
Example 1. 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"
// The following statement is true,
// because defined msgArray [99] element.
if (msgArray .length == 100)
[Link]("The length is 100.")
See also examples for onError.
Example 2: Two-dimensional array. The following code creates a two-dimensional array and
displays the results.
a = new Array(4)
for (i=0; i < 4; i++) {
a[i] = new Array(4)
for (j=0; j < 4; j++) {
Page No:28
a[i][j] = "["+i+","+j+"]"
}
}
for (i=0; i < 4; i++) {
str = "Row "+i+":"
for (j=0; j < 4; j++) {
str += a[i][j]
}
[Link](str,"<p>")
}
This example displays the following results:
Multidimensional array test
Row 0:[0,0][0,1][0,2][0,3]
Row 1:[1,0][1,1][1,2][1,3]
Row 2:[2,0][2,1][2,2][2,3]
Row 3:[3,0][3,1][3,2][3,3]
Properties
index
For an array created by a regular expression match, the zero-based index of the match in the string.
input
For an array created by a regular expression match, reflects the original string against which the
regular expression was matched.
length
An integer that specifies the number of elements in an array. 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.
Property of Array
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 < [Link]; i++) {
if ([Link][i].selected == true) {
return [Link][i].text
}
}
}
The following example shortens the array statesUS to a length of 50 if the current length is greater
than 50.
if ([Link] > 50) {
[Link]=50
alert("The U.S. has only 50 states. New length is " + [Link])
}
prototype
Represents the prototype for this class. You can use the prototype to add properties or methods to all
instances of a class. For information on prototypes, see [Link].
Page No:29
Property of Array
Methods
concat
Joins two arrays and returns a new array.
Method of Array
Syntax
concat(arrayName2)
Parameters
Description
concat does not alter the original arrays, but returns a "one level deep" copy that contains copies of
the same elements combined from the original arrays. Elements of the original arrays are copied into
the new array as follows:
Object references (and not the actual object) -- concat copies object references into the new
array. Both the original and new array refer to the same object. If a referenced object changes,
the changes are visible to both the new and original arrays.
Strings and numbers (not String and Number objects)-- concat copies strings and numbers
into the new array. Changes to the string or number in one array does not affect the other
arrays.
If a new element is added to either array, the other array is not affected.
join
Joins all elements of an array into a string.
Method of Array
Syntax
join(separator)
Parameters
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.
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")
[Link]([Link]() +"<BR>")
[Link]([Link](", ") +"<BR>")
[Link]([Link](" + ") +"<BR>")
This code produces the following output:
Page No:30
Wind,Rain,Fire
Wind, Rain, Fire
Wind + Rain + Fire
See also
[Link]
pop
Removes the last element from an array and returns that element. This method changes the length of
the array.
Method of Array
Syntax
pop()
Parameters
None.
Example
The following code displays the myFish array before and after removing its last element. It also
displays the removed element:
myFish = ["angel", "clown", "mandarin", "surgeon"];
[Link]("myFish before: " + myFish);
popped = [Link]();
[Link]("myFish after: " + myFish);
[Link]("popped this element: " + popped);
This example displays the following:
push
Adds one or more elements to the end of an array and returns that last element added. This method
changes the length of the array.
Method of Array
Syntax
Parameters
elt1, ..., eltN The elements to add to the end of the array.
Description
The behavior of the push method is analogous to the push function in Perl 4. Note that this behavior
is different in Perl 5.
Example
Page No:31
The following code displays the myFish array before and after adding elements to its end. It also
displays the last element added:
myFish = ["angel", "clown"];
[Link]("myFish before: " + myFish);
pushed = [Link]("drum", "lion");
[Link]("myFish after: " + myFish);
[Link]("pushed this element last: " + pushed);
This example displays the following:
reverse
Transposes the elements of an array: the first array element becomes the last and the last becomes the
first.
Method of Array
Syntax
reverse()
Parameters
None
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")
[Link]()
This code changes myArray so that:
myArray[0] is "three"
myArray[1] is "two"
myArray[2] is "one"
shift
Removes the first element from an array and returns that element. This method changes the length of
the array.
Method of Array
Syntax
shift()
Parameters
None.
Example
The following code displays the myFish array before and after removing its first element. It also
displays the removed element:
Page No:32
myFish = ["angel", "clown", "mandarin", "surgeon"];
[Link]("myFish before: " + myFish);
shifted = [Link]();
[Link]("myFish after: " + myFish);
[Link]("Removed this element: " + shifted);
This example displays the following:
slice
Extracts a section of an array and returns a new array.
Method of Array
Syntax
slice(begin,end)
Parameters
slice extracts up to but not including end. slice(1,4) extracts the second element
through the fourth element (elements indexed 1, 2, and 3)
As a negative index, end indicates an offset from the end of the sequence. slice(2,-
1) extracts the third element through the second to last element in the sequence.
If end is omitted, slice extracts to the end of the sequence.
Description
slice does not alter the original array, but returns a new "one level deep" copy that contains copies
of the elements sliced from the original array. Elements of the original array are copied into the new
array as follows:
Object references (and not the actual object) -- slice copies object references into the new array.
Both the original and new array refer to the same object. If a referenced object changes, the changes
are visible to both the new and original arrays.
Strings and numbers (not String and Number objects)-- slice copies strings and numbers into the
new array. Changes to the string or number in one array does not affect the other array.
If a new element is added to either array, the other array is not affected.
Example
In the following example, slice creates a new array, newCar, from myCar. Both include a reference
to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the
change.
<SCRIPT LANGUAGE="JavaScript1.2">
//Using slice, create newCar from myCar.
myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}}
myCar = [myHonda, 2, "cherry condition", "purchased 1997"]
newCar = [Link](0,2)
//Write the values of myCar, newCar, and the color of myHonda
// referenced from both arrays.
Page No:33
[Link]("myCar = " + myCar + "<BR>")
[Link]("newCar = " + newCar + "<BR>")
[Link]("myCar[0].color = " + myCar[0].color + "<BR>")
[Link]("newCar[0].color = " + newCar[0].color + "<BR><BR>")
//Change the color of myHonda.
[Link] = "purple"
[Link]("The new color of my Honda is " + [Link] + "<BR><BR>")
//Write the color of myHonda referenced from both arrays.
[Link]("myCar[0].color = " + myCar[0].color + "<BR>")
[Link]("newCar[0].color = " + newCar[0].color + "<BR>")
</SCRIPT>
This script writes:
myCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2,
"cherry condition", "purchased 1997"]
newCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2]
myCar[0].color = red newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple
splice
Changes the content of an array, adding new elements while removing old elements.
Method of Array
Syntax
Parameters
Description
If you specify a different number of elements to insert than the number you're removing, the array
will have a different length at the end of the call.
If howMany is 1, this method returns the single element that it removes. If howMany is more than 1, the
method returns an array containing the removed elements.
Examples
Page No:34
This script displays:
myFish: ["angel", "clown", "mandarin", "surgeon"]
After adding 1: ["angel", "clown", "drum", "mandarin", "surgeon"]
removed is: undefined
After removing 1: ["angel", "clown", "drum", "surgeon"]
removed is: mandarin
After replacing 1: ["angel", "clown", "trumpet", "surgeon"]
removed is: drum
After replacing 2: ["parrot", "anemone", "blue", "trumpet", "surgeon"]
removed is: ["angel", "clown"]
sort
Sorts the elements of an array.
Method of Array
Syntax
sort(compareFunction)
Parameters
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.
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 in a numeric sort 9 comes 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:
The behavior of the sort method changed between Navigator 3.0 and Navigator 4.0.
In Navigator 3.0, on some platforms, the sort method does not work. This method works on all
platforms for Navigator 4.0.
Page No:35
In Navigator 4.0, this method no longer converts undefined elements to null; instead it sorts them to
the high end of the array. For example, assume you have this script:
<SCRIPT>
a = new Array();
a[0] = "Ant";
a[5] = "Zebra";
function writeArray(x) {
for (i = 0; i < [Link]; i++) {
[Link](x[i]);
if (i < [Link]-1) [Link](", ");
}
}
writeArray(a);
[Link]();
[Link]("<BR><BR>");
writeArray(a);
</SCRIPT>
In Navigator 3.0, JavaScript prints:
ant, null, null, null, null, zebra
ant, null, null, null, null, zebra
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
}
[Link]("<B>stringArray:</B> " + [Link]() +"<BR>")
[Link]("<B>Sorted:</B> " + [Link]() +"<P>")
[Link]("<B>numberArray:</B> " + [Link]() +"<BR>")
[Link]("<B>Sorted without a compare function:</B> " + [Link]()
+"<BR>")
[Link]("<B>Sorted with compareNumbers:</B> " +
[Link](compareNumbers) +"<P>")
[Link]("<B>numericStringArray:</B> " + [Link]() +"<BR>")
[Link]("<B>Sorted without a compare function:</B> " +
[Link]() +"<BR>")
[Link]("<B>Sorted with compareNumbers:</B> " +
[Link](compareNumbers) +"<P>")
[Link]("<B>mixedNumericArray:</B> " + [Link]() +"<BR>")
[Link]("<B>Sorted without a compare function:</B> " +
[Link]() +"<BR>")
[Link]("<B>Sorted with compareNumbers:</B> " +
[Link](compareNumbers) +"<BR>")
</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
Page No:36
toString
Returns a string representing the specified object.
Method of Array
Syntax
toString()
Parameters
None.
Description
Every object has a toString method that is automatically called when it is to be represented as a text
value or when an object is referred to in a string concatenation.
You can use toString within your own code to convert an object into a string, and you can create
your own function to be called in place of the default toString method.
For Array objects, the built-in toString method joins the array and returns one string containing
each array element separated by commas. For example, the following code creates an array and uses
toString to convert the array to a string while writing output.
unshift
Adds one or more elements to the beginning of an array and returns the new length of the array.
Method of Array
Syntax
[Link](elt1,..., eltN)
Parameters
Example
The following code displays the myFish array before and after adding elements to it.
myFish = ["angel", "clown"];
[Link]("myFish before: " + myFish);
unshifted = [Link]("drum", "lion");
[Link]("myFish after: " + myFish);
[Link]("New length: " + unshifted);
This example displays the following:
Boolean
Page No:37
The Boolean object is an object wrapper for a boolean value.
Created by
Parameters
value The initial value of the Boolean object. The value is converted to a boolean value, if
necessary. If value is omitted or is 0, null, false, or the empty string (""), the object has an
initial value of false. All other values, including the string "false", create an object with an
initial value of true.
Description
Use a Boolean object when you need to convert a non-boolean value to a boolean value. You can use
the Boolean object any place JavaScript expects a primitive boolean value. JavaScript returns the
primitive value of the Boolean object by automatically invoking the valueOf method.
Property Summary
Method Summary
Examples
The following examples create Boolean objects with an initial value of false:
bNoParam = new Boolean()
bZero = new Boolean(0)
bNull = new Boolean(null)
bEmptyString = new Boolean("")
bfalse = new Boolean(false)
The following examples create Boolean objects with an initial value of true:
btrue = new Boolean(true)
btrueString = new Boolean("true")
bfalseString = new Boolean("false")
bSuLin = new Boolean("Su Lin")
Properties
prototype
Represents the prototype for this class. You can use the prototype to add properties or methods to all
instances of a class. For information on prototypes, see [Link].
Property of Boolean
Methods
toString
Returns a string representing the specified object.
Method of Boolean
Syntax
Page No:38
toString()
Parameters
None.
Description
Every object has a toString method that is automatically called when it is to be represented as a text
value or when an object is referred to in a string concatenation.
You can use toString within your own code to convert an object into a string, and you can create
your own function to be called in place of the default toString method.
For Boolean objects and values, the built-in toString method returns "true" or "false" depending
on the value of the boolean object. In the following code, [Link] returns "true".
Date
Lets you work with dates and times.
Core object
Created by
Parameters
Description
If you supply no arguments, the constructor creates a Date object for today's date and time. If you
supply some arguments, but not others, the missing arguments are set to 0. If you supply any
arguments, you must supply at least the year, month, and day. You can omit the hours, minutes, and
seconds.
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.
Property Summary
Page No:39
Method Summary
getDate Returns the day of the month for the specified date.
getDay Returns the day of the week for the specified date.
getHours Returns the hour in the specified date.
getMinutes Returns the minutes in the specified date.
getMonth Returns the month in the specified date.
getSeconds Returns the seconds in the specified date.
getTime Returns the numeric value corresponding to the time for the specified date.
getTimezoneOffset Returns the time-zone offset in minutes for the current locale.
getYear Returns the year in the specified date.
parse Returns the number of milliseconds in a date string since January 1, 1970,
00:00:00, local time.
setDate Sets the day of the month for a specified date.
setHours Sets the hours for a specified date.
setMinutes Sets the minutes for a specified date.
setMonth Sets the month for a specified date.
setSeconds Sets the seconds for a specified date.
setTime Sets the value of a Date object.
setYear Sets the year for a specified date.
toGMTString Converts a date to a string, using the Internet GMT conventions.
toLocaleString Converts a date to a string, using the current locale's conventions.
UTC Returns the number of milliseconds in a Date object since January 1, 1970,
00:00:00, Universal Coordinated Time (GMT).
Examples
Properties
prototype
Represents the prototype for this class. You can use the prototype to add properties or methods to all
instances of a class. For information on prototypes, see [Link].
Methods
getDate
Returns the day of the month for the specified date.
Syntax
getDate()
Parameters
None
Description
Page No:40
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 = [Link]()
See also
[Link]
getDay
Returns the day of the week for the specified date.
Syntax
getDay()
Parameters
None
Description
The value returned by getDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for
Monday, 2 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. December 25, 1995, is a Monday.
Xmas95 = new Date("December 25, 1995 23:15:00")
weekday = [Link]()
getHours
Returns the hour for the specified date.
Syntax
getHours()
Parameters
None
Description
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 = [Link]()
getMinutes
Page No:41
Returns the minutes in the specified date.
Method of Date
Syntax
getMinutes()
Parameters
None
Description
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 = [Link]()
See also
[Link]
getMonth
Returns the month in the specified date.
Method of Date
Syntax
getMonth()
Parameters
None
Description
The value returned by getMonth is an integer between 0 and 11. 0 corresponds to January, 1 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 = [Link]()
getSeconds
Returns the seconds in the current time.
Method of Date
Syntax
Page No:42
getSeconds()
Parameters
None
Description
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 = [Link]()
getTime
Returns the numeric value corresponding to the time for the specified date.
Syntax
getTime()
Parameters
None
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
getTimezoneOffset
Returns the time-zone offset in minutes for the current locale.
Method of Date
Syntax
getTimezoneOffset()
Parameters
None
Description
The time-zone offset is the difference between local time and Greenwich Mean Time (GMT).
Daylight savings time prevents this value from being a constant.
Examples
Page No:43
x = new Date()
currentTimeZoneOffsetInHours = [Link]()/60
getYear
Returns the year in the specified date.
Method of Date
Syntax
getYear()
Parameters
None
Description
For years between and including 1900 and 1999, the value returned by getYear is the year
minus 1900. For example, if the year is 1976, the value returned is 76.
For years less than 1900 or greater than 1999, the value returned by getYear is the four-digit
year. For example, if the year is 1856, the value returned is 1856. If the year is 2026, the value
returned is 2026.
Examples
Example 1. The second statement assigns the value 95 to the variable year.
Xmas = new Date("December 25, 1995 23:15:00")
year = [Link]()
Example 2. The second statement assigns the value 2000 to the variable year.
Xmas = new Date("December 25, 2000 23:15:00")
year = [Link]()
Example 3. The second statement assigns the value 95 to the variable year, representing the year
1995.
[Link](95)
year = [Link]()
See also
[Link]
parse
Returns the number of milliseconds in a date string since January 1, 1970, 00:00:00, local time.
Method of Date
Static
Syntax
[Link](dateString)
Parameters
:
dateString A string representing a date.
Description
Page No:44
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 parse is a static method of Date, you always use it as [Link](), rather than as a
method of a Date object you created.
Examples
If IPOdate is an existing Date object, then you can set it to August 9, 1995 as follows:
[Link]([Link]("Aug 9, 1995"))
setDate
Sets the day of the month for a specified date.
Method of Date
Syntax
setDate(dayValue)
Parameters
Examples
The second statement below changes the day for theBigDay to July 24 from its original value.
theBigDay = new Date("July 27, 1962 23:30:00")
[Link](24)
See also
[Link]
setHours
Sets the hours for a specified date.
Method of Date
Syntax
setHours(hoursValue)
Parameters
Examples
[Link](7)
Page No:45
See also
[Link]
setMinutes
Sets the minutes for a specified date.
Method of Date
Syntax
setMinutes(minutesValue)
Parameters
Examples
[Link](45)
setMonth
Sets the month for a specified date.
Method of Date
Syntax
setMonth(monthValue)
Parameters
monthValue An integer between 0 and 11 (representing the months January through December).
Examples
[Link](6)
setSeconds
Sets the seconds for a specified date.
Method of Date
Syntax
setSeconds(secondsValue)
Parameters
Examples
[Link](30)
See also
Page No:46
[Link]
setTime
Sets the value of a Date object.
Method of Date
Syntax
setTime(timevalue)
Parameters
timevalue An integer representing the number of milliseconds since 1 January 1970 00:00:00.
Description
Use the setTime method to help assign a date and time to another Date object.
Examples
setYear
Sets the year for a specified date.
Method of Date
Syntax
setYear(yearValue)
Parameters
yearValue An integer.
Description
If yearValue is a number between 0 and 99 (inclusive), then the year for dateObjectName is set to
1900 + yearValue. Otherwise, the year for dateObjectName is set to yearValue.
Examples
Note that there are two ways to set years in the 20th century.
[Link](96)
Example 2. The year is set to 1996.
[Link](1996)
Example 3. The year is set to 2000.
[Link](2000)
toGMTString
Page No:47
Converts a date to a string, using the Internet GMT conventions.
Method of Date
Syntax
toGMTString()
Parameters
None
Description
The exact format of the value returned by toGMTString varies according to the platform.
Examples
toLocaleString
Converts a date to a string, using the current locale's conventions.
Syntax
toLocaleString()
Parameters
None
Description
If you pass a date using toLocaleString, be aware that different platforms assemble the string in
different ways. Using methods such as getHours, getMinutes, and getSeconds gives more portable
results.
Examples
UTC
Returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, Universal
Coordinated Time (GMT).
Syntax
Page No:48
Parameters
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 [Link](), rather than as a method of
a Date object you created.
Examples
The following statement creates a Date object using GMT instead of local time:
gmtDate = new Date([Link](96, 11, 1, 0, 0, 0))
Function
Specifies a string of JavaScript code to be compiled as a function.
Core object
Created by
Parameters
arg1, arg2, ... (Optional) Names to be used by the function as formal argument names. Each
argN
must be a string that corresponds to a valid JavaScript identifier; for example "x"
or "theForm".
functionBody A string containing the JavaScript statements comprising the function definition.
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.
In addition to defining functions as described here, you can also use the function statement, as
described in the JavaScript Guide.
Property Summary
Method Summary
Page No:49
toString Returns a string representing the specified object.
The following code assigns a function to the variable setBGColor. This function sets the current
document's background color.
var setBGColor = new Function("[Link]='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:
[Link]=setBGColor
<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() {
[Link]='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.
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:
The following code assigns a function to a window's onFocus event handler (the event handler must
be spelled in all lowercase):
[Link] = new Function("[Link]='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:
[Link]()
Event handlers do not take arguments, so you cannot declare any arguments in the Function
constructor for an event handler.
Examples
Page No:50
Example 1. 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("[Link]='antiquewhite'")
frames[0].onblur = new Function("[Link]='lightgrey'")
Example 2. You can determine whether a function exists by comparing the function name to null. In
the following example, func1 is called if the function noFunc does not exist; otherwise func2 is
called. Notice that the window name is needed when referring to the function name noFunc.
if ([Link] == null)
func1()
else func2()
Properties
arguments
An array corresponding to the arguments passed to a function.
Property of Function
Description
You can call a function with more arguments than it is formally declared to accept by using the
arguments array. This technique is useful if a function can be passed a variable number of
arguments. You can use [Link] to determine the number of arguments passed to the
function, and then treat each argument by using the arguments array.
The arguments array is available only within a function declaration. Attempting to access the
arguments array outside a function declaration results in an error.
The this keyword does not refer to the currently executing function, so you must refer to functions
and Function objects by name, even within the function body. In JavaScript 1.2, arguments includes
these additional properties:
For example, the following script demonstrates several of the arguments properties:
<SCRIPT>
function b(z) {
[Link](arguments.z + "<BR>")
[Link] ([Link].x + "<BR>")
return 99
}
function a(x, y) {
return b(534)
}
[Link] (a(2,3) + "<BR>")
</SCRIPT>
This displays:
534
2
99
Page No:51
99 is what a(2,3) returns.
Examples
This example defines a function that creates 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) {
[Link]("<" + type + "L>")
for (var i=1; i<[Link]; i++) {
[Link]("<LI>" + [Link][i])
[Link]("</" + type + "L>")
}
}
You can pass any number of arguments to this function, and it displays each argument as an item in
the type of list indicated. For example, the following call to the function
list("U", "One", "Two", "Three")
results in this output:
<UL>
<LI>One
<LI>Two
<LI>Three
</UL>
In server-side JavaScript, you can display the same output by calling the write function instead of
using [Link].
arity
When the LANGUAGE attribute of the SCRIPT tag is "JavaScript1.2", this property indicates the number
of arguments expected by a function.
Property of Function
Description
arity is external to the function, and indicates how many arguments the function expects. By
contrast, [Link] provides the number of arguments actually passed to the function.
Example
arity = 2
length = 3
caller
Returns the name of the function that invoked the currently executing function.
Property of Function
Description
The caller property is available only within the body of a function. If used outside a function
declaration, the caller property is null.
Page No:52
If the currently executing function was invoked by the top level of a JavaScript program, the value of
caller is null.
The this keyword does not refer to the currently executing function, so you must refer to functions
and Function objects by name, even within the function body.
If you use it in a string context, you get the result of calling [Link]. That
is, the decompiled canonical source form of the function.
You can also call the calling function, if you know what arguments it might want. Thus, a
called function can call its caller without knowing the name of the particular caller, provided
it knows that all of its callers have the same form and fit, and that they will not call the called
function again unconditionally (which would result in infinite recursion).
Examples
prototype
A value from which instances of a particular class are created. Every object that can be created by
calling a constructor function has an associated prototype property.
Property of Object
Description
You can add new properties or methods to an existing class by adding them to the prototype
associated with the constructor function for that class. The syntax for adding a new property or
method is:
[Link] = value
where
fun The name of the constructor function object you want to change.
name The name of the property or method to be created.
value The value initially assigned to the new property or method.
If you add a new property to the prototype for an object, then all objects created with that object's
constructor function will have that new property, even if the objects existed before you created the
new property. For example, assume you have the following statements:
Example
The following example creates a method, str_rep, and uses the statement [Link]
= str_rep to add the method to all String objects. All objects created with new String() then
have that method, even objects already created. The example then creates an alternate method and
Page No:53
adds that to one of the String objects using the statement [Link] = fake_rep. The str_rep
method of the remaining String objects is not altered.
var s1 = new String("a")
var s2 = new String("b")
var s3 = new String("c")
// Create a repeat-string-N-times method for all String objects
function str_rep(n) {
var s = "", t = [Link]()
while (--n >= 0) s += t
return s
}
[Link] = str_rep
// Display the results
[Link]("<P>[Link](3) is " + [Link](3)) // "aaa"
[Link]("<BR>[Link](5) is " + [Link](5)) // "bbbbb"
[Link]("<BR>[Link](2) is " + [Link](2)) // "cc"
// Create an alternate method and assign it to only one String variable
function fake_rep(n) {
return "repeat " + this + n + " times."
}
[Link] = fake_rep
[Link]("<P>[Link](1) is " + [Link](1)) // "repeat a 1 times."
[Link]("<BR>[Link](4) is " + [Link](4)) // "bbbb"
[Link]("<BR>[Link](6) is " + [Link](6)) // "cccccc"
This example produces the following output:
[Link](3) is aaa
[Link](5) is bbbbb
[Link](2) is cc
[Link](1) is repeat a1 times.
[Link](4) is bbbb
[Link](6) is cccccc
The function in this example also works on String objects not created with the String constructor.
The following code returns "zzz".
"z".rep(3)
Methods
toString
Returns a string representing the specified object.
Method of Function
Syntax
toString()
Parameters
None.
Description
Every object has a toString method that is automatically called when it is to be represented as a text
value or when an object is referred to in a string concatenation.
You can use toString within your own code to convert an object into a string, and you can create
your own function to be called in place of the default toString method.
For Function objects, the built-in toString method decompiles the function back into the
JavaScript source that defines the function. This string includes the function keyword, the argument
list, curly braces, and function body.
For example, assume you have the following code that defines the Dog object type and creates
theDog, an object of type Dog:
Page No:54
function Dog(name,breed,color,sex) {
[Link]=name
[Link]=breed
[Link]=color
[Link]=sex
}
theDog = new Dog("Gabby","Lab","chocolate","girl")
Any time Dog is used in a string context, JavaScript automatically calls the toString function, which
returns the following string:
Math
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.
Core object.
Created by
The Math object is a top-level, predefined JavaScript object. You can automatically access it without
using a constructor or calling a method.
Description
All properties and methods of Math are static. You refer to the constant PI as [Link] and you call
the sine function as [Link](x), where x is the method's argument. Constants are defined with the
full precision of real numbers in JavaScript.
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)
}
Property Summary
Method Summary
Page No:55
exp Returns Enumber, where number is the argument, and E is Euler's constant, the base of the
natural logarithms.
floor Returns the largest integer less than or equal to a number.
log Returns the natural logarithm (base E) of a number.
max Returns the greater of two numbers.
min Returns the lesser of two numbers.
pow Returns base to the exponent power, that is, baseexponent.
random Returns a pseudo-random number between 0 and 1.
round Returns the value of a number rounded to the nearest integer.
sin Returns the sine of a number.
sqrt Returns the square root of a number.
tan Returns the tangent of a number.
Properties
E
Euler's constant and the base of natural logarithms, approximately 2.718.
Property of Math
Static, Read-only
Examples
Description
Because E is a static property of Math, you always use it as Math.E, rather than as a property of a
Math object you created.
LN10
The natural logarithm of 10, approximately 2.302.
Property of Math
Static, Read-only
Examples
Description
Because LN10 is a static property of Math, you always use it as Math.LN10, rather than as a property
of a Math object you created.
LN2
The natural logarithm of 2, approximately 0.693.
Property of Math
Static, Read-only
Page No:56
Examples
Description
Because LN2 is a static property of Math, you always use it as Math.LN2, rather than as a property of a
Math object you created.
LOG10E
The base 10 logarithm of E (approximately 0.434).
Property of Math
Static, Read-only
Examples
Description
Because LOG10E is a static property of Math, you always use it as Math.LOG10E, rather than as a
property of a Math object you created.
LOG2E
The base 2 logarithm of E (approximately 1.442).
Property of Math
Static, Read-only
Examples
Description
Because LOG2E is a static property of Math, you always use it as Math.LOG2E, rather than as a
property of a Math object you created.
PI
The ratio of the circumference of a circle to its diameter, approximately 3.14159.
Property of Math
Static, Read-only
Examples
Page No:57
function getPi() {
return [Link]
}
Description
Because PI is a static property of Math, you always use it as [Link], rather than as a property of a
Math object you created.
SQRT1_2
The square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
Property of Math
Static, Read-only
Examples
Description
Because SQRT1_2 is a static property of Math, you always use it as Math.SQRT1_2, rather than as a
property of a Math object you created.
SQRT2
The square root of 2, approximately 1.414.
Property of Math
Static, Read-only
Examples
Description
Because SQRT2 is a static property of Math, you always use it as Math.SQRT2, rather than as a
property of a Math object you created.
Methods
abs
Returns the absolute value of a number.
Method of Math
Static
Syntax
abs(x)
Parameters
Page No:58
x A number
Examples
Description
Because abs is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
acos
Returns the arccosine (in radians) of a number.
Method of Math
Static
Syntax
acos(x)
Parameters
x A number
Description
The acos method returns a numeric value between 0 and pi radians. If the value of number is outside
this range, it returns 0.
Because acos is a static method of Math, you always use it as [Link](), rather than as a method
of a Math object you created.
Examples
asin
Returns the arcsine (in radians) of a number.
Method of Math
Static
Syntax
asin(x)
Parameters
x A number
Page No:59
Description
The asin method returns a numeric value between -pi/2 and pi/2 radians. If the value of number is
outside this range, it returns 0.
Because asin is a static method of Math, you always use it as [Link](), rather than as a method
of a Math object you created.
Examples
atan
Returns the arctangent (in radians) of a number.
Method of Math
Static
Syntax
atan(x)
Parameters
x A number
Description
The atan method returns a numeric value between -pi/2 and pi/2 radians.
Because atan is a static method of Math, you always use it as [Link](), rather than as a method
of a Math object you created.
Examples
atan2
Returns the arctangent of the quotient of its arguments.
Method of Math
Static
Syntax
atan2(y, x)
Parameters
Page No:60
y, x Number
Description
The atan2 method returns a numeric value between -pi and pi representing the angle theta of an
(x,y) point. This is the counterclockwise angle, measured in radians, between the positive X axis, and
the point (x,y). Note that the arguments to this function pass the y-coordinate first and the x-
coordinate second.
atan2 is passed separate x and y arguments, and atan is passed the ratio of those two arguments.
Because atan2 is a static method of Math, you always use it as Math.atan2(), rather than as a
method of a Math object you created.
Examples
ceil
Returns the smallest integer greater than or equal to a number.
Method of Math
Static
Syntax
ceil(x)
Parameters
x A number
Description
Because ceil is a static method of Math, you always use it as [Link](), rather than as a method
of a Math object you created.
Examples
cos
Returns the cosine of a number.
Method of Math
Static
Syntax
cos(x)
Page No:61
Parameters
x A number
Description
The cos method returns a numeric value between -1 and 1, which represents the cosine of the angle.
Because cos is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
exp
Returns Ex, where x is the argument, and E is Euler's constant, the base of the natural logarithms.
Method of Math
Static
Syntax
exp(x)
Parameters
x A number
Description
Because exp is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
floor
Returns the largest integer less than or equal to a number.
Syntax
floor(x)
Parameters
x A number
Page No:62
Description
Because floor is a static method of Math, you always use it as [Link](), rather than as a
method of a Math object you created.
Examples
See also
[Link]
log
Returns the natural logarithm (base E) of a number.
Syntax
log(x)
Parameters
x A number
Description
If the value of number is outside the suggested range, the return value is always -
1.797693134862316e+308.
Because log is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
See also
[Link], [Link]
max
Returns the larger of two numbers.
Syntax
max(x,y)
Parameters
Page No:63
x, y Numbers.
Description
Because max is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
See also
[Link]
min
Returns the smaller of two numbers.
Syntax
min(x,y)
Parameters
x, y Numbers.
Description
Because min is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
See also
[Link]
pow
Returns base to the exponent power, that is, baseexponent.
Syntax
pow(x,y)
Parameters
Page No:64
base The base number
exponent The exponent to which to raise base
Description
Because pow is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
function raisePower(x,y) {
return [Link](x,y)
}
If x is 7 and y is 2, raisePower returns 49 (7 to the power of 2).
See also
[Link], [Link]
random
Returns a pseudo-random number between 0 and 1. The random number generator is seeded from the
current time, as in Java.
Syntax
random()
Parameters
None.
Description
Because random is a static method of Math, you always use it as [Link](), rather than as a
method of a Math object you created.
Examples
round
Returns the value of a number rounded to the nearest integer.
Syntax
round(x)
Parameters
x A number
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.
Page No:65
Because round is a static method of Math, you always use it as [Link](), rather than as a
method of a Math object you created.
Examples
sin
Returns the sine of a number.
Syntax
sin(x)
Parameters
x A number
Description
The sin method returns a numeric value between -1 and 1, which represents the sine of the argument.
Because sin is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
See also
sqrt
Returns the square root of a number.
Syntax
sqrt(x)
Parameters
x A number
Description
Page No:66
If the value of number is outside the required range, sqrt returns 0.
Because sqrt is a static method of Math, you always use it as [Link](), rather than as a method
of a Math object you created.
Examples
tan
Returns the tangent of a number.
Syntax
tan(x)
Parameters
x A number
Description
The tan method returns a numeric value that represents the tangent of the angle.
Because tan is a static method of Math, you always use it as [Link](), rather than as a method of
a Math object you created.
Examples
Number
Lets you work with numeric values. The Number object is an object wrapper for primitive numeric
values.
Created by
Parameters
Description
Page No:67
To access its constant properties, which represent the largest and smallest representable
numbers, positive and negative infinity, and the Not-a-Number value.
To create numeric objects that you can add properties to. Most likely, you will rarely need to
create a Number object.
The properties of Number are properties of the class itself, not of individual Number objects.
Navigator 4.0: Number(x) now produces NaN rather than an error if x is a string that does not contain
a well-formed numeric literal. For example,
x=Number("three");
[Link](x + "<BR>");
prints NaN
Property Summary
Method Summary
Examples
Example 1. The following example uses the Number object's properties to assign values to several
numeric variables:
biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = [Link]
Example 2. The following example creates a Number object, myNum, then adds a description
property to all Number objects. Then a value is assigned to the myNum object's description property.
myNum = new Number(65)
[Link]=null
[Link]="wind speed"
Properties
MAX_VALUE
The maximum numeric value representable in JavaScript.
Description
The MAX_VALUE property has a value of approximately 1.79E+308. Values larger than MAX_VALUE are
represented as "Infinity".
Because MAX_VALUE is a static property of Number, you always use it as Number.MAX_VALUE, rather
than as a property of a Number object you created.
Examples
The following code multiplies two numeric values. If the result is less than or equal to MAX_VALUE,
the func1 function is called; otherwise, the func2 function is called.
Page No:68
if (num1 * num2 <= Number.MAX_VALUE)
func1()
else
func2()
MIN_VALUE
The smallest positive numeric value representable in JavaScript.
Property of Number
Static, Read-only
Description
The MIN_VALUE property is the number closest to 0, not the most negative number, that JavaScript
can represent.
MIN_VALUE has a value of approximately 2.22E-308. Values smaller than MIN_VALUE ("underflow
values") are converted to 0.
Because MIN_VALUE is a static property of Number, you always use it as Number.MIN_VALUE, rather
than as a property of a Number object you created.
Examples
The following code divides two numeric values. If the result is greater than or equal to MIN_VALUE,
the func1 function is called; otherwise, the func2 function is called.
if (num1 / num2 >= Number.MIN_VALUE)
func1()
else
func2()
NaN
A special value representing Not-A-Number. This value is represented as the unquoted literal NaN.
Property of Number
Read-only
Description
NaNis always unequal to any other number, including NaN itself; you cannot check for the not-a-
number value by comparing to [Link]. Use the isNaN function instead.
You might use the NaN property to indicate an error condition for a function that should return a valid
number.
Examples
In the following example, if month has a value greater than 12, it is assigned NaN, and a message is
displayed indicating valid values.
var month = 13
if (month < 1 || month > 12) {
month = [Link]
alert("Month must be between 1 and 12.")
}
Page No:69
See also
NEGATIVE_INFINITY
A special numeric value representing negative infinity. This value is displayed as "-Infinity".
Property of Number
Static, Read-only
Description
This value behaves mathematically like infinity; for example, anything multiplied by infinity is
infinity, and anything divided by infinity is 0.
Examples
In the following example, the variable smallNumber is assigned a value that is smaller than the
minimum value. When the if statement executes, smallNumber has the value "-Infinity", so the
func1 function is called.
var smallNumber = -Number.MAX_VALUE*10
if (smallNumber == Number.NEGATIVE_INFINITY)
func1()
else
func2()
POSITIVE_INFINITY
A special numeric value representing infinity. This value is displayed as "Infinity".
Property of Number
Static, Read-only
Description
This value behaves mathematically like infinity; for example, anything multiplied by infinity is
infinity, and anything divided by infinity is 0.
Examples
In the following example, the variable bigNumber is assigned a value that is larger than the maximum
value. When the if statement executes, bigNumber has the value "Infinity", so the func1 function
is called.
var bigNumber = Number.MAX_VALUE * 10
if (bigNumber == Number.POSITIVE_INFINITY)
func1()
else
func2()
Page No:70
prototype
Represents the prototype for this class. You can use the prototype to add properties or methods to all
instances of a class. For information on prototypes, see [Link].
Property of Number
Methods
toString
Returns a string representing the specified object.
Method of Number
Syntax
toString()
toString(radix)
Parameters
radix (Optional) An integer between 2 and 16 specifying the base to use for representing numeric
values.
Description
Every object has a toString method that is automatically called when it is to be represented as a text
value or when an object is referred to in a string concatenation.
You can use toString within your own code to convert an object into a string, and you can create
your own function to be called in place of the default toString method.
You can use toString on numeric values, but not on numeric literals:
Object
Object is the primitive JavaScript object type. All JavaScript objects are descended from Object.
That is, all JavaScript objects have the methods defined for Object.
Core object
Created by
Parameters
None
Property Summary
Page No:71
Method Summary
eval Evaluates a string of JavaScript code in the context of the specified object.
toStringReturns a string representing the specified object.
unwatch Removes a watchpoint from a property of the object.
valueOf Returns the primitive value of the specified object.
watch Adds a watchpoint to a property of the object.
Properties
constructor
Specifies the function that creates an object's prototype. Note that the value of this property is a
reference to the function itself, not a string containing the function's name.
Property of Object
Description
Examples
The following example creates a prototype, Tree, and an object of that type, theTree. The example
then displays the constructor property for the object theTree.
function Tree(name) {
[Link]=name
}
theTree = new Tree("Redwood")
[Link]("<B>[Link] is</B> " +
[Link] + "<P>")
This example displays the following output:
[Link] is function Tree(name) { [Link] = name; }
prototype
Represents the prototype for this class. You can use the prototype to add properties or methods to all
instances of a class. For more information, see [Link].
Property of Object
Methods
eval
Evaluates a string of JavaScript code in the context of this object.
Method of Object
Syntax
eval(string)
Parameters
Page No:72
string Any string representing a JavaScript expression, statement, or sequence of statements. The
expression can include variables and properties of existing objects.
Description
The argument of the eval method is a string. If the string represents an expression, eval evaluates
the expression. If the argument represents one or more JavaScript statements, eval performs the
statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic
expressions automatically.
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.
NOTE: In Navigator 2.0, eval was a top-level function. In Navigator 3.0 eval was
also a method of every object. The ECMA-262 standard for JavaScript made eval
available only as a top-level function. For this reason, in Navigator 4.0, eval is once
again a top-level function. In Navigator 4.02, [Link](str) is equivalent in all
scopes to with(obj)eval(str), except of course that the latter is a statement, not an
expression.
Examples
Example 1. The following example creates breed as a property of the object myDog, and also as a
variable. The first write statement uses eval('breed') without specifying an object; the string
"breed" is evaluated without regard to any object, and the write method displays "Shepherd",
which is the value of the breed variable. The second write statement uses [Link]('breed')
which specifies the object myDog; the string "breed" is evaluated with regard to the myDog object,
and the write method displays "Lab", which is the value of the breed property of the myDog object.
function Dog(name,breed,color) {
[Link]=name
[Link]=breed
[Link]=color
}
myDog = new Dog("Gabby")
[Link]="Lab"
var breed='Shepherd'
[Link]("<P>" + eval('breed'))
[Link]("<BR>" + [Link]('breed'))
Example 2. The following example uses eval within a function that defines an object type, stone.
The statement flint = new stone("x=42") creates the object flint with the properties x, y, z, and
z2. The write statements display the values of these properties as 42, 43, 44, and 45, respectively.
function stone(str) {
[Link]("this."+str)
[Link]("this.y=43")
this.z=44
this["z2"] = 45
}
flint = new stone("x=42")
[Link]("<BR>flint.x is " + flint.x)
[Link]("<BR>flint.y is " + flint.y)
[Link]("<BR>flint.z is " + flint.z)
[Link]("<BR>flint.z2 is " + flint.z2)
See also
eval
toString
Page No:73
Returns a string representing the specified object.
Method of Object
Syntax
toString()
toString(radix)
Parameters
radix (Optional) An integer between 2 and 16 specifying the base to use for representing numeric
values.
Security
Navigator 3.0: This method is tainted by default for the following objects: Button, Checkbox,
FileUpload, Hidden, History, Link, Location, Password, Radio, Reset, Select, Submit, Text,
and Textarea.
Description
Every object has a toString method that is automatically called when it is to be represented as a text
value or when an object is referred to in a string concatenation. For example, the following examples
require theDog to be represented as a string:
[Link](theDog)
[Link]("The dog is " + theDog)
You can use toString within your own code to convert an object into a string, and you can create
your own function to be called in place of the default toString method.
Every object type has a built-in toString method, which JavaScript calls whenever it needs to
convert an object to a string. If an object has no string value and no user-defined toString method,
toString returns "[object type]", where type is the object type or the name of the constructor
function that created the object. For example, if for an Image object named sealife defined as
shown below, [Link]() returns [object Image].
<IMG NAME="sealife" SRC="images\[Link]" ALIGN="left" VSPACE="10">
Some built-in classes have special definitions for their toString methods. See the descriptions of this
method for these objects:
Array, Boolean, Connection, database, DbPool, Function, Number
You can create a function to be called in place of the default toString method. The toString
method takes no arguments and should return a string. The toString method you create can be any
value you want, but it will be most useful if it carries information about the object.
The following code defines the Dog object type and creates theDog, an object of type Dog:
function Dog(name,breed,color,sex) {
[Link]=name
[Link]=breed
[Link]=color
[Link]=sex
}
theDog = new Dog("Gabby","Lab","chocolate","girl")
The following code creates dogToString, the function that will be used in place of the default
toString method. This function generates a string containing each property, of the form "property
= value;".
function dogToString() {
var ret = "Dog " + [Link] + " is ["
for (var prop in this)
Page No:74
ret += " " + prop + " is " + this[prop] + ";"
return ret + "]"
}
The following code assigns the user-defined function to the object's toString method:
[Link] = dogToString
With the preceding code in place, any time theDog is used in a string context, JavaScript
automatically calls the dogToString function, which returns the following string:
Dog Gabby is [ name is Gabby; breed is Lab; color is chocolate; sex is girl; toString is
function dogToString() { var ret = "Object " + [Link] + " is ["; for (var prop in this)
{ ret += " " + prop + " is " + this[prop] + ";"; } return ret + "]"; } ;]
An object's toString method is usually invoked by JavaScript, but you can invoke it yourself as
follows:
alert([Link]())
Examples
Example 1: The location object. The following example prints the string equivalent of the current
location.
[Link]("[Link]() is " + [Link]() + "<BR>")
The output is as follows:
[Link]() is [Link]
Example 2: Object with no string value. Assume you have an Image object named sealife
defined as follows:
<IMG NAME="sealife" SRC="images\[Link]" ALIGN="left" VSPACE="10">
Because the Image object itself has no special toString method, [Link]() returns the
following:
[object Image]
Example 3: The radix parameter. The following example prints the string equivalents of the
numbers 0 through 9 in decimal and binary.
for (x = 0; x < 10; x++) {
[Link]("Decimal: ", [Link](10), " Binary: ",
[Link](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
See also
[Link]
unwatch
Removes a watchpoint set with the watch method.
Method of Object
Syntax
unwatch(prop)
Parameters
Page No:75
Description
The JavaScript debugger has functionality similar to that provided by this method, as well as other
debugging options. For information on the debugger, see Getting Started with Netscape JavaScript
Debugger.
Example
See watch.
valueOf
Returns the primitive value of the specified object.
Method of Object
Syntax
valueOf()
Parameters
None
Description
Every object has a valueOf method that is automatically called when it is to be represented as a
primitive value. If an object has no primitive value, valueOf returns the object itself.
You can use valueOf within your own code to convert an object into a primitive value, and you can
create your own function to be called in place of the default valueOf method.
Every object type has a built-in valueOf method, which JavaScript calls whenever it needs to convert
an object to a primitive value.
You rarely need to invoke the valueOf method yourself. JavaScript automatically invokes it when
encountering an object where a primitive value is expected.
Table 4.2 shows the object types for which the valueOf method is most useful. Most other objects
have no primitive value.
You can create a function to be called in place of the default valueOf method. Your function must
take no arguments.
Suppose you have an object type myNumberType and you want to create a valueOf method for it. The
following code assigns a user-defined function to the object's valueOf method:
Page No:76
With the preceding code in place, any time an object of type myNumberType is used in a context
where it is to be represented as a primitive value, JavaScript automatically calls the function defined
in the preceding code.
An object's valueOf method is usually invoked by JavaScript, but you can invoke it yourself as
follows:
[Link]()
NOTE: Objects in string contexts convert via the toString method, which is
different from String objects converting to string primitives using valueOf. All
string objects have a string conversion, if only "[object type]". But many objects
do not convert to number, boolean, or function.
watch
Watches for a property to be assigned a value and runs a function when that occurs.
Method of Object
Syntax
watch(prop, handler)
Parameters
Description
Watches for assignment to a property named prop in this object, calling handler(prop, oldval,
newval) whenever prop is set and storing the return value in that property. A watchpoint can filter
(or nullify) the value assignment, by returning a modified newval (or oldval).
If you delete a property for which a watchpoint has been set, that watchpoint does not disappear. If
you later recreate the property, the watchpoint is still in effect.
The JavaScript debugger has functionality similar to that provided by this method, as well as other
debugging options. For information on the debugger, see Getting Started with Netscape JavaScript
Debugger.
Example
<script language="JavaScript1.2">
o = {p:1}
[Link]("p",
function (id,oldval,newval) {
[Link]("o." + id + " changed from "
+ oldval + " to " + newval)
return newval
})
o.p = 2
o.p = 3
delete o.p
o.p = 4
[Link]('p')
o.p = 5
</script>
This script displays the following:
Page No:77
o.p changed from 1 to 2
o.p changed from 2 to 3
o.p changed from 3 to 4
RegExp
A regular expression object contains the pattern of a regular expression. It has properties and methods
for using that regular expression to find and replace matches in strings.
In addition to the properties of an individual regular expression object that you create using the
RegExp constructor function, the predefined RegExp object has static properties that are set whenever
any regular expression is used.
Core object
Created by
/pattern/flags
The constructor function is used as follows:
new RegExp("pattern", "flags")
Parameters
g: global match
i: ignore case
gi: both global match and ignore case
Notice that the parameters to the literal format do not use quotation marks to indicate strings, while
the parameters to the constructor function do use quotation marks. So the following expressions
create the same regular expression:
/ab+c/i
new RegExp("ab+c", "i")
Description
When using the constructor function, the normal string escape rules (preceding special characters
with \ when included in a string) are necessary. For example, the following are equivalent:
re = new RegExp("\\w+")
re = /\w+/
Table 4.3 provides a complete list and description of the special characters that can be used in regular
expressions.
Character Meaning
\ For characters that are usually treated literally, indicates that the next character is special
and not to be interpreted literally.
For example, /b/ matches the character 'b'. By placing a backslash in front of b, that is
by using /\b/, the character becomes special to mean match a word boundary.
-or-
Page No:78
For characters that are usually treated specially, indicates that the next character is not
special and should be interpreted literally.
For example, * is a special character that means 0 or more occurrences of the preceding
character should be matched; for example, /a*/ means match 0 or more a's. To match *
literally, precede the it with a backslash; for example, /a\*/ matches 'a*'.
^ Matches beginning of input or line.
For example, /^A/ does not match the 'A' in "an A," but does match it in "An A."
$ Matches end of input or line.
For example, /t$/ does not match the 't' in "eater", but does match it in "eat"
* Matches the preceding character 0 or more times.
For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled",
but nothing in "A goat grunted".
+ Matches the preceding character 1 or more times. Equivalent to {1,}.
For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy."
? Matches the preceding character 0 or 1 time.
For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle."
. (The decimal point) matches any single character except the newline character.
For example, /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but not 'nay'.
(x) Matches 'x' and remembers the match.
For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring
can be recalled from the resulting array's elements [1], ..., [n], or from the predefined
RegExp object's properties $1, ..., $9.
x|y Matches either 'x' or 'y'.
For example, /green|red/ matches 'green' in "green apple" and 'red' in "red apple."
{n} Where n is a positive integer. Matches exactly n occurrences of the preceding character.
For example, /a{2}/ doesn't match the 'a' in "candy," but it matches all of the a's in
"caandy," and the first two a's in "caaandy."
{n,} Where n is a positive integer. Matches at least n occurrences of the preceding character.
For example, /a{2,} doesn't match the 'a' in "candy", but matches all of the a's in
"caandy" and in "caaaaaaandy."
{n,m} Where n and m are positive integers. Matches at least n and at most m occurrences of the
preceding character.
For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the first two a's in
"caandy," and the first three a's in "caaaaaaandy" Notice that when matching
"caaaaaaandy", the match is "aaa", even though the original string had more a's in it.
[xyz] A character set. Matches any one of the enclosed characters. You can specify a range of
characters by using a hyphen.
For example, [abcd] is the same as [a-c]. They match the 'b' in "brisket" and the 'c' in
"ache".
[^xyz] A negated or complemented character set. That is, it matches anything that is not
enclosed in the brackets. You can specify a range of characters by using a hyphen.
For example, [^abc] is the same as [^a-c]. They initially match 'r' in "brisket" and 'h'
in "chop."
[\b] Matches a backspace. (Not to be confused with \b.)
\b Matches a word boundary, such as a space. (Not to be confused with [\b].)
For example, /\bn\w/ matches the 'no' in "noonday";/\wy\b/ matches the 'ly' in
"possibly yesterday."
\B Matches a non-word boundary.
For example, /\w\Bn/ matches 'on' in "noonday", and /y\B\w/ matches 'ye' in "possibly
yesterday."
\cX Where X is a control character. Matches a control character in a string.
For example, /\cM/ matches control-M in a string.
\d Matches a digit character. Equivalent to [0-9].
For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."
Page No:79
\D Matches any non-digit character. Equivalent to [^0-9].
For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."
\f Matches a form-feed.
\n Matches a linefeed.
\r Matches a carriage return.
\s Matches a single white space character, including space, tab, form feed, line feed.
Equivalent to [ \f\n\r\t\v].
for example, /\s\w*/ matches ' bar' in "foo bar."
\S Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v].
For example, /\S/\w* matches 'foo' in "foo bar."
\t Matches a tab
\v Matches a vertical tab.
\w Matches any alphanumeric character including the underscore. Equivalent to [A-Za-z0-
9_].
For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."
\W Matches any non-word character. Equivalent to [^A-Za-z0-9_].
For example, /\W/ or /[^$A-Za-z0-9_]/ matches '%' in "50%."
\n Where n is a positive integer. A back reference to the last substring matching the n
parenthetical in the regular expression (counting left parentheses).
For example, /apple(,)\sorange\1/ matches 'apple, orange', in "apple, orange, cherry,
peach." A more complete example follows this table.
Note: If the number of left parentheses is less than the number specified in \n, the \n is
taken as an octal escape as described in the next row.
\ooctal Where \ooctal is an octal escape value or \xhex is a hexadecimal escape value. Allows
\xhex
you to embed ASCII codes into regular expressions.
The literal notation provides compilation of the regular expression when the expression is evaluated.
Use literal notation when the regular expression will remain constant. For example, if you use literal
notation to construct a regular expression used in a loop, the regular expression won't be recompiled
on each iteration.
The constructor of the regular expression object, for example, new RegExp("ab+c"), provides
runtime compilation of the regular expression. Use the constructor function when you know the
regular expression pattern will be changing, or you don't know the pattern and are getting it from
another source, such as user input. Once you have a defined regular expression, and if the regular
expression is used throughout the script and may change, you can use the compile method to compile
a new regular expression for efficient reuse.
A separate predefined RegExp object is available in each window; that is, each separate thread of
JavaScript execution gets its own RegExp object. Because each script runs to completion without
interruption in a thread, this assures that different scripts do not overwrite values of the RegExp
object.
The predefined RegExp object contains the static properties input, multiline, lastMatch,
lastParen, leftContext, rightContext, and $1 through $9. The input and multiline properties
can be preset. The values for the other static properties are set after execution of the exec and test
methods of an individual regular expression object, and after execution of the match and replace
methods of String.
Property Summary
Note that several of the RegExp properties have both long and short (Perl-like) names. Both names
always refer to the same value. Perl is the programming language from which JavaScript modeled its
regular expressions.
$1, ..., $9 Parenthesized substring matches, if any.
$_ See input.
Page No:80
$* See multiline.
$& See lastMatch.
$+ See lastParen.
$` See leftContext.
$' See rightContext.
global Whether or not to test the regular expression against all possible matches in a string,
or only against the first.
ignoreCase Whether or not to ignore case while attempting a match in a string.
input The string against which a regular expression is matched.
lastIndex The index at which to start the next match.
lastMatch The last matched characters.
lastParen The last parenthesized substring match, if any.
leftContext The substring preceding the most recent match.
multiline Whether or not to search in strings across multiple lines.
rightContext The substring following the most recent match.
source The text of the pattern.
Method Summary
Examples
Example 1. The following script uses the replace method to switch the words in the string. For the
replacement text, the script uses the values of the $1 and $2 properties of the global RegExp object.
Note that the RegExp object name is not be prepended to the $ properties when they are passed as the
second argument to the replace method.
<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr=[Link](re, "$2, $1");
[Link](newstr)
</SCRIPT>
This displays "Smith, John".
Example 2. In the following example, [Link] is set by the Change event. In the getInfo
function, the exec method uses the value of [Link] as its argument. Note that RegExp is
prepended to the $ properties.
<HTML>
<SCRIPT LANGUAGE="JavaScript1.2">
function getInfo() {
re = /(\w+)\s(\d+)/;
[Link]();
[Link](RegExp.$1 + ", your age is " + RegExp.$2);
}
</SCRIPT>
Enter your first name and your age, and then press Enter.
<FORM>
<INPUT TYPE:"TEXT" NAME="NameAge" onChange="getInfo(this);">
</FORM>
</HTML>
Properties
$1, ..., $9
Properties that contain parenthesized substring matches, if any.
Page No:81
Property of RegExp
Static, Read-only
Description
Because input is static, it is not a property of an individual regular expression object. Instead, you
always use it as [Link].
The number of possible parenthesized substrings is unlimited, but the predefined RegExp object can
only hold the last nine. You can access all parenthesized substrings through the returned array's
indexes.
These properties can be used in the replacement text for the [Link] method. When used
this way, do not prepend them with RegExp. The example below illustrates this. When parentheses
are not included in the regular expression, the script interprets $n's literally (where n is a positive
integer).
Examples
The following script uses the replace method to switch the words in the string. For the replacement
text, the script uses the values of the $1 and $2 properties of the global RegExp object. Note that the
RegExp object name is not be prepended to the $ properties when they are passed as the second
argument to the replace method.
<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr=[Link](re, "$2, $1");
[Link](newstr)
</SCRIPT>
This displays "Smith, John".
$_
See input.
$*
See multiline.
$&
See lastMatch.
$+
See lastParen.
$`
See leftContext.
$'
See rightContext.
global
Page No:82
Whether or not the "g" flag is used with the regular expression.
Property of RegExp
Read-only
Description
The value of global is true if the "g" flag was used; otherwise, false. The "g" flag indicates that
the regular expression should be tested against all possible matches in a string.
You cannot change this property directly. However, calling the compile method changes the value of
this property.
ignoreCase
Whether or not the "i" flag is used with the regular expression.
Property of RegExp
Read-only
Description
The value of ignoreCase is true if the "i" flag was used; otherwise, false. The "i" flag indicates
that case should be ignored while attempting a match in a string.
You cannot change this property directly. However, calling the compile method changes the value of
this property.
input
The string against which a regular expression is matched. $_ is another name for the same property.
Property of RegExp
Static
Description
Because input is static, it is not a property of an individual regular expression object. Instead, you
always use it as [Link].
The script or the browser can preset the input property. If preset and if no string argument is
explicitly provided, the value of input is used as the string argument to the exec or test methods of
the regular expression object. input is set by the browser in the following cases:
When an event handler is called for a TEXT form element, input is set to the value of the
contained text.
When an event handler is called for a TEXTAREA form element, input is set to the value of the
contained text. Note that multiline is also set to true so that the match can be executed over
the multiple lines of text.
When an event handler is called for a SELECT form element, input is set to the value of the
selected text.
When an event handler is called for a Link object, input is set to the value of the text
between <A HREF=...> and </A>.
Page No:83
The value of the input property is cleared after the event handler completes.
lastIndex
A read/write integer property that specifies the index at which to start the next match.
Property of RegExp
Description
This property is set only if the regular expression used the "g" flag to indicate a global search. The
following rules apply:
If lastIndex is greater than the length of the string, [Link] and [Link] fail, and
lastIndex is set to 0.
If lastIndex is equal to the length of the string and if the regular expression matches the
empty string, then the regular expression matches input starting at lastIndex.
If lastIndex is equal to the length of the string and if the regular expression does not match
the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
Otherwise, lastIndex is set to the next position following the most recent match.
lastMatch
The last matched characters. $& is another name for the same property.
Property of RegExp
Static, Read-only
Description
Because lastMatch is static, it is not a property of an individual regular expression object. Instead,
you always use it as [Link].
lastParen
The last parenthesized substring match, if any. $+ is another name for the same property.
Property of RegExp
Static, Read-only
Description
Because lastParen is static, it is not a property of an individual regular expression object. Instead,
you always use it as [Link].
leftContext
The substring preceding the most recent match. $` is another name for the same property.
Property of RegExp
Static, Read-only
Page No:84
Description
Because leftContext is static, it is not a property of an individual regular expression object. Instead,
you always use it as [Link].
multiline
Reflects whether or not to search in strings across multiple lines. $* is another name for the same
property.
Property of RegExp
Static
Description
Because multiline is static, it is not a property of an individual regular expression object. Instead,
you always use it as [Link].
The value of multiline is true if multiple lines are searched, false if searches must stop at line
breaks.
The script or the browser can preset the multiline property. When an event handler is called for a
TEXTAREA form element, the browser sets multiline to true. multiline is cleared after the event
handler completes. This means that, if you've preset multiline to true, it is reset to false after the
execution of any event handler.
rightContext
The substring following the most recent match. $' is another name for the same property.
Property of RegExp
Static, Read-only
Description
source
A read-only property that contains the text of the pattern, excluding the forward slashes and "g" or
"i" flags.
Property of RegExp
Read-only
Description
You cannot change this property directly. However, calling the compile method changes the value of
this property.
Methods
compile
Compiles a regular expression object during execution of a script.
Method of RegExp
Page No:85
Syntax
[Link](pattern, flags)
Parameters
regexp The name of the regular expression. It can be a variable name or a literal.
pattern A string containing the text of the regular expression.
flags (Optional) If specified, flags can have one of the following 3 values:
Description
Use the compile method to compile a regular expression created with the RegExp constructor
function. This forces compilation of the regular expression once only which means the regular
expression isn't compiled each time it is encountered. Use the compile method when you know the
regular expression will remain constant (after getting its pattern) and will be used repeatedly
throughout the script.
You can also use the compile method to change the regular expression during execution. For
example, if the regular expression changes, you can use the compile method to recompile the object
for more efficient repeated use.
Calling this method changes the value of the regular expression's source, global, and ignoreCase
properties.
exec
Executes the search for a match in a specified string. Returns a result array.
Method of RegExp
Syntax
[Link](str)
regexp(str)
Parameters
regexp The name of the regular expression. It can be a variable name or a literal.
str (Optional) The string against which to match the regular expression. If omitted, the value of
[Link] is used.
Description
As shown in the syntax description, a regular expression's exec method call be called either directly,
(with [Link](str)) or indirectly (with regexp(str)).
If you are executing a match simply to find true or false, use the test method or the String
search method.
If the match succeeds, the exec method returns an array and updates properties of the regular
expression object and the predefined regular expression object, RegExp. If the match fails, the exec
method returns null.
Page No:86
Consider the following example:
<SCRIPT LANGUAGE="JavaScript1.2">
//Match one d followed by one or more b's followed by one d
//Remember matched b's and the following d
//Ignore case
myRe=/d(b+)(d)/ig;
myArray = [Link]("cdbBdbsbz");
</SCRIPT>
If your regular expression uses the "g" flag, you can use the exec method multiple times to find
successive matches in the same string. When you do so, the search starts at the substring of str
specified by the regular expression's lastIndex property. For example, assume you have this script:
<SCRIPT LANGUAGE="JavaScript1.2">
myRe=/ab*/g;
str = "abbcdefabh"
myArray = [Link](str);
[Link]("Found " + myArray[0] +
". Next match starts at " + [Link])
mySecondArray = [Link](str);
[Link]("Found " + mySecondArray[0] +
". Next match starts at " + [Link])
</SCRIPT>
This script displays the following text:
Examples
In the following example, the user enters a name and the script executes a match against the input. It
then cycles through the array to see if other names match the user's name.
Page No:87
This script assumes that first names of registered party attendees are preloaded into the array A,
perhaps by gathering them from a party database.
<HTML>
<SCRIPT LANGUAGE="JavaScript1.2">
A = ["Frank", "Emily", "Jane", "Harry", "Nick", "Beth", "Rick",
"Terrence", "Carol", "Ann", "Terry", "Frank", "Alice", "Rick",
"Bill", "Tom", "Fiona", "Jane", "William", "Joan", "Beth"]
function lookup() {
firstName = /\w+/i();
if (!firstName)
[Link] ([Link] + " isn't a name!");
else {
count = 0;
for (i=0; i<[Link]; i++)
if (firstName[0].toLowerCase() == A[i].toLowerCase()) count++;
if (count ==1)
midstring = " other has ";
else
midstring = " others have ";
[Link] ("Thanks, " + count + midstring + "the same name!")
}
}
</SCRIPT>
Enter your first name and then press Enter.
<FORM> <INPUT TYPE:"TEXT" NAME="FirstName" onChange="lookup(this);"> </FORM>
</HTML>
test
Executes the search for a match between a regular expression and a specified string. Returns true or
false.
Method of RegExp
Syntax
[Link](str)
Parameters
regexp The name of the regular expression. It can be a variable name or a literal.
str (Optional) The string against which to match the regular expression. If omitted, the value of
[Link] is used.
Description
When you want to know whether a pattern is found in a string use the test method (similar to the
[Link] method); for more information (but slower execution) use the exec method (similar
to the [Link] method).
Example
The following example prints a message which depends on the success of the test:
function testinput(re, str){
if ([Link](str))
midstring = " contains ";
else
midstring = " does not contain ";
[Link] (str + midstring + [Link]);
}
String
Page No:88
An object representing a series of characters in a string.
Core object
Created by
Parameters
Description
The String object is a built-in JavaScript object. You an treat any JavaScript string as a String
object.
A string can be represented as a literal enclosed by single or double quotation marks; for example,
"Netscape" or 'Netscape'.
Property Summary
Method Summary
Examples
Example 4: Pass a string among scripts in different windows or frames. The following code
creates two string variables and opens a second window:
Properties
length
The length of the string.
Property of String
Read-only
Description
Examples
prototype
Page No:90
Represents the prototype for this class. You can use the prototype to add properties or methods to all
instances of a class. For information on prototypes, see [Link].
Property of String
Methods
anchor
Creates an HTML anchor that is used as a hypertext target.
Method of String
Syntax
anchor(nameAttribute)
Parameters
nameAttribute A string.
Description
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 [Link] array.
Examples
The following example opens the msgWindow window and creates an anchor for the table of contents:
var myString="Table of Contents"
[Link]([Link]("contents_anchor"))
The previous example produces the same output as the following HTML:
<A NAME="contents_anchor">Table of Contents</A>
In server-side JavaScript, you can generate this HTML by calling the write function instead of using
[Link].
See also
[Link]
big
Causes a string to be displayed in a big font as if it were in a BIG tag.
Method of String
Syntax
big()
Parameters
None
Description
Page No:91
Use the big method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
Examples
The following example uses string methods to change the size of a string:
var worldString="Hello, world"
[Link]([Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link](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
[Link], [Link]
blink
Causes a string to blink as if it were in a BLINK tag.
Method of String
Syntax
blink()
Parameters
None
Description
Use the blink method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
Examples
The following example uses string methods to change the formatting of a string:
var worldString="Hello, world"
[Link]([Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
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
bold
Causes a string to be displayed as bold as if it were in a B tag.
Method of String
Syntax
Page No:92
bold()
Parameters
None
Description
Use the bold method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
Examples
The following example uses string methods to change the formatting of a string:
var worldString="Hello, world"
[Link]([Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
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
charAt
Returns the specified character from the string.
Method of String
Syntax
charAt(index)
Parameters
index An integer between 0 and 1 less than the length of the 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 in a string called stringName is [Link] - 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"
[Link]("The character at index 0 is " + [Link](0))
[Link]("The character at index 1 is " + [Link](1))
[Link]("The character at index 2 is " + [Link](2))
[Link]("The character at index 3 is " + [Link](3))
[Link]("The character at index 4 is " + [Link](4))
These lines display the following:
In server-side JavaScript, you can display the same output by calling the write function instead of
using [Link].
See also
charCodeAt
Returns a number indicating the ISO-Latin-1 codeset value of the character at the given index.
Method of String
Syntax
charCodeAt(index)
Parameters
index (Optional) An integer between 0 and 1 less than the length of the string. The default value is
0.
Description
The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII
character set.
Example
The following example returns 65, the ISO-Latin-1 codeset value for A.
"ABC".charCodeAt(0)
concat
Combines the text of two strings and returns a new string.
Method of String
Syntax
concat(string2)
Parameters
Description
concat combines the text from two strings and returns a new string. Changes to the text in one string
do not affect the other string.
Example
Page No:94
str3=[Link](str2)
[Link](str1)
[Link](str2)
[Link](str3)
</SCRIPT>
This writes:
fixed
Causes a string to be displayed in fixed-pitch font as if it were in a TT tag.
Method of String
Syntax
fixed()
Parameters
None
Description
Use the fixed method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
Examples
The following example uses the fixed method to change the formatting of a string:
var worldString="Hello, world"
[Link]([Link]())
The previous example produces the same output as the following HTML:
<TT>Hello, world</TT>
fontcolor
Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.
Method of String
Syntax
fontcolor(color)
Parameters
color A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals
for color names are listed in Appendix B, "Color Values," in the JavaScript Guide.
Description
Use the fontcolor method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
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".
Page No:95
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"
[Link]([Link]("maroon") +
" is maroon in this line")
[Link]("<P>" + [Link]("salmon") +
" is salmon in this line")
[Link]("<P>" + [Link]("red") +
" is red in this line")
[Link]("<P>" + [Link]("8000") +
" is maroon in hexadecimal in this line")
[Link]("<P>" + [Link]("FA8072") +
" is salmon in hexadecimal in this line")
[Link]("<P>" + [Link]("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
Causes a string to be displayed in the specified font size as if it were in a <FONT SIZE=size> tag.
Method of String
Syntax
fontsize(size)
Parameters
size An integer between 1 and 7, a string representing a signed integer between 1 and 7.
Description
Use the fontsize method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
When you specify size as an integer, you set the size of stringName to one of the 7 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"
[Link]([Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link](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
Page No:96
[Link], [Link]
fromCharCode
Returns a string created by using the specified sequence ISO-Latin-1 codeset values.
Method of String
Static
Syntax
Parameters
num1, ..., numN A sequence of numbers that are ISO-Latin-1 codeset values.
Description
Examples
indexOf
Returns the index within the calling String object of the first occurrence of the specified value,
starting the search at fromIndex, or -1 if the value is not found.
Method of String
Syntax
indexOf(searchValue, fromIndex)
Parameters
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 of a string called stringName is [Link] - 1.
The indexOf method is case sensitive. For example, the following expression returns -1:
Page No:97
"Blue Whale".indexOf("blue")
Examples
Example 1. The following example uses indexOf and lastIndexOf to locate values in the string
"Brave new world."
var anyString="Brave new world"
//Displays 8
[Link]("<P>The index of the first w from the beginning is " +
[Link]("w"))
//Displays 10
[Link]("<P>The index of the first w from the end is " +
[Link]("w"))
//Displays 6
[Link]("<P>The index of 'new' from the beginning is " +
[Link]("new"))
//Displays 6
[Link]("<P>The index of 'new' from the end is " +
[Link]("new"))
Example 2. The following example defines two string variables. The variables contain the same
string except that the second string contains uppercase letters. The first writeln method displays 19.
But because the indexOf method is case sensitive, the string "cheddar" is not found in
myCapString, so the second writeln method displays -1.
myString="brie, pepper jack, cheddar"
myCapString="Brie, Pepper Jack, Cheddar"
[Link]('[Link]("cheddar") is ' +
[Link]("cheddar"))
[Link]('<P>[Link]("cheddar") is ' +
[Link]("cheddar"))
Example 3. The following example sets count to the number of occurrences of the letter x in the
string str:
count = 0;
pos = [Link]("x");
while ( pos != -1 ) {
count++;
pos = [Link]("x",pos+1);
}
See also
italics
Causes a string to be italic, as if it were in an I tag.
Method of String
Syntax
italics()
Parameters
None
Description
Use the italics method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
Examples
The following example uses string methods to change the formatting of a string:
var worldString="Hello, world"
Page No:98
[Link]([Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
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
lastIndexOf
Returns the index within the calling String object of the last occurrence of the specified value. The
calling string is searched backward, starting at fromIndex, or -1 if not found.
Method of String
Syntax
lastIndexOf(searchValue, fromIndex)
Parameters
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 [Link] - 1.
The lastIndexOf method is case sensitive. For example, the following expression 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
[Link]("<P>The index of the first w from the beginning is " +
[Link]("w"))
//Displays 10
[Link]("<P>The index of the first w from the end is " +
[Link]("w"))
//Displays 6
[Link]("<P>The index of 'new' from the beginning is " +
[Link]("new"))
//Displays 6
[Link]("<P>The index of 'new' from the end is " +
[Link]("new"))
In server-side JavaScript, you can display the same output by calling the write function instead of
using [Link].
See also
Syntax
link(hrefAttribute)
Parameters
hrefAttribute Any string that specifies the HREF attribute of the A tag; it should be a valid URL
(relative or absolute).
Description
Use the link method to programmatically create a hypertext link, and then call write or writeln to
display the link in a document. In server-side JavaScript, use the write function to display the link.
Links created with the link method become elements in the links array of the document object. See
[Link].
Examples
The following example displays the word "Netscape" as a hypertext link that returns the user to the
Netscape home page:
var hotText="Netscape"
var URL="[Link]
[Link]("Click to return to " + [Link](URL))
The previous example produces the same output as the following HTML:
Click to return to <A HREF="[Link]
See also
Anchor
match
Used to match a regular expression against a string.
Method of String
Syntax
match(regexp)
Parameters
Description
If you want to execute a global match, or a case insensitive match, include the g (for global) and i
(for ignore case) flags in the regular expression. These can be included separately or together. The
following two examples below show how to use these flags with match.
Note
If you execute a match simply to find true or false, use [Link] or the regular expression
test method.
Page No:100
Examples
Example 1. In the following example, match is used to find 'Chapter' followed by 1 or more numeric
characters followed by a decimal point and numeric character 0 or more times. The regular
expression includes the i flag so that case will be ignored.
<SCRIPT>
str = "For more information, see Chapter [Link]";
re = /(chapter \d+(\.\d)*)/i;
found = [Link](re);
[Link](found);
</SCRIPT>
This returns the array containing Chapter [Link],Chapter [Link],.1
'Chapter [Link]' is the first match and the first value remembered from (Chapter \d+(\.\
d)*).
Example 2. The following example demonstrates the use of the global and ignore case flags with
match.
<SCRIPT>
str = "abcDdcba";
newArray = [Link](/d/gi);
[Link](newArray);
</SCRIPT>
The returned array contains D, d.
replace
Used to find a match between a regular expression and a string, and to replace the matched substring
with a new substring.
Method of String
Syntax
replace(regexp, newSubStr)
Parameters
regexp The name of the regular expression. It can be a variable name or a literal.
newSubStr The string to put in place of the string found with regexp. This string can include the
RegExp properties $1, ..., $9, lastMatch, lastParen, leftContext, and
rightContext.
Description
This method does not change the String object it is called on; it simply returns a new string.
If you want to execute a global search and replace, or a case insensitive search, include the g (for
global) and i (for ignore case) flags in the regular expression. These can be included separately or
together. The following two examples below show how to use these flags with replace.
Examples
Example 1. In the following example, the regular expression includes the global and ignore case
flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges.'
<SCRIPT>
re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=[Link](re, "oranges");
Page No:101
[Link](newstr)
</SCRIPT>
This prints "oranges are round, and oranges are juicy."
Example 2. In the following example, the regular expression is defined in replace and includes the
ignore case flag.
<SCRIPT>
str = "Twas the night before Xmas...";
newstr=[Link](/xmas/i, "Christmas");
[Link](newstr)
</SCRIPT>
This prints "Twas the night before Christmas..."
Example 3. The following script switches the words in the string. For the replacement text, the script
uses the values of the $1 and $2 properties.
<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = [Link](re, "$2, $1");
[Link](newstr)
</SCRIPT>
This prints "Smith, John".
search
Executes the search for a match between a regular expression and this String object.
Method of String
Syntax
search(regexp)
Parameters
Description
If successful, search returns the index of the regular expression inside the string. Otherwise, it
returns -1.
When you want to know whether a pattern is found in a string use search (similar to the regular
expression test method); for more information (but slower execution) use match (similar to the
regular expression exec method).
Example
The following example prints a message which depends on the success of the test.
function testinput(re, str){
if ([Link](re) != -1)
midstring = " contains ";
else
midstring = " does not contain ";
[Link] (str + midstring + [Link]);
}
slice
Page No:102
Extracts a section of a string and returns a new string.
Method of String
Syntax
slice(beginslice,endSlice)
Parameters
Description
slice extracts the text from one string and returns a new string. Changes to the text in one string do
not affect the other string.
slice extracts up to but not including endSlice. [Link](1,4) extracts the second character
through the fourth character (characters indexed 1, 2, and 3).
As a negative index, endSlice indicates an offset from the end of the string. [Link](2,-1)
extracts the third character through the second to last character in the string.
Example
small
Causes a string to be displayed in a small font, as if it were in a SMALL tag.
Method of String
Syntax
small()
Parameters
None
Description
Use the small method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
Examples
The following example uses string methods to change the size of a string:
var worldString="Hello, world"
[Link]([Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link](7))
The previous example produces the same output as the following HTML:
Page No:103
<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>
See also
[Link], [Link]
split
Splits a String object into an array of strings by separating the string into substrings.
Method of String
Syntax
split(separator, limit)
Parameters
separator (Optional) 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.
limit (Optional) Integer specifying a limit on the number of splits to be found.
Description
When found, separator is removed from the string and the substrings are returned in an array. If
separator is omitted, the array contains one element consisting of the entire string.
It can take a regular expression argument, as well as a fixed string, by which to split the object
string. If separator is a regular expression, any included parenthesis cause submatches to be
included in the returned array.
It can take a limit count so that it won't include trailing empty elements in the resulting array.
If you specify LANGUAGE="JavaScript1.2" in the SCRIPT tag, [Link](" ") splits on
any run of 1 or more white space characters including spaces, tabs, line feeds, and carriage
returns.
Examples
Example 1. The following example defines a function that splits a string into an array of strings
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 = [Link](separator)
[Link] ('<P>The original string is: "' + stringToSplit + '"')
[Link] ('<BR>The separator is: "' + separator + '"')
[Link] ("<BR>The array has " + [Link] + " elements: ")
for (var i=0; i < [Link]; i++) {
[Link] (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=","
Page No:104
splitString(tempestString,space)
splitString(tempestString)
splitString(monthString,comma)
This example produces the following output:
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 / Dec /
Example 2. Consider the following script:
<SCRIPT LANGUAGE="JavaScript1.2">
str="She sells seashells \nby the\n seashore"
[Link](str + "<BR>")
a=[Link](" ")
[Link](a)
</SCRIPT>
Using LANGUAGE="JavaScript1.2", this script produces
"She", "sells", "seashells", "by", "the", "seashore"
Without LANGUAGE="JavaScript1.2", this script splits only on single space characters, producing
"She", "sells", , , , "seashells", "by", , , "the", "seashore"
Example 3. In the following example, split looks for 0 or more spaces followed by a semicolon
followed by 0 or more spaces and, when found, removes the spaces from the string. nameList is the
array returned as a result of split.
<SCRIPT>
names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
[Link] (names + "<BR>" + "<BR>");
re = /\s*;\s*/;
nameList = [Link] (re);
[Link](nameList);
</SCRIPT>
This prints two lines; the first line prints the original string, and the second line prints the resulting
array.
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
Harry Trump,Fred Barney,Helen Rigby,Bill Abel,Chris Hand
Example 4. In the following example, split looks for 0 or more spaces in a string and returns the
first 3 splits that it finds.
<SCRIPT LANGUAGE="JavaScript1.2">
myVar = " Hello World. How are you doing? ";
splits = [Link](" ", 3);
[Link](splits)
</SCRIPT>
This script displays the following:
["Hello", "World.", "How"]
See also
strike
Causes a string to be displayed as struck-out text, as if it were in a STRIKE tag.
Method of String
Syntax
strike()
Page No:105
Parameters
None
Description
Use the strike method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to display the string.
Examples
The following example uses string methods to change the formatting of a string:
var worldString="Hello, world"
[Link]([Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
[Link]("<P>" + [Link]())
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
sub
Causes a string to be displayed as a subscript, as if it were in a SUB tag.
Method of String
Syntax
sub()
Parameters
None
Description
Use the sub method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to generate the HTML.
Examples
The following example uses the sub and sup methods to format a string:
var superText="superscript"
var subText="subscript"
[Link]("This is what a " + [Link]() + " looks like.")
[Link]("<P>This is what a " + [Link]() + " 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
[Link]
Page No:106
substr
Returns the characters in a string beginning at the specified location through the specified number of
characters.
Method of String
in Navigator 2.0, LiveWire 1.0
Syntax
substr(start, length)
Parameters
Description
start is a character index. The index of the first character is 0, and the index of the last character is 1
less than the length of the string. substr begins extracting characters at start and collects length
number of characters.
If start is positive and is the length of the string or longer, substr returns no characters.
If start is negative, substr uses it as a character index from the end of the string. If start is
negative and abs(start) is larger than the length of the string, substr uses 0 is the start index.
Example
See also
substring
substring
Returns a subset of a String object.
Method of String
Syntax
substring(indexA, indexB)
Page No:107
Parameters
indexA An integer between 0 and 1 less than the length of the string.
indexB An integer between 0 and 1 less than the length of the string.
Description
substring extracts characters from indexA up to but not including indexB. In particular:
If indexA is greater than indexB, JavaScript produces a runtime error (out of memory).
Without LANGUAGE="JavaScript1.2",
If indexA is greater than indexB, JavaScript returns a substring beginning with indexB and
ending with indexA - 1.
Examples
Example 1. The following example uses substring to display characters from the string
"Netscape":
var anyString="Netscape"
//Displays "Net"
[Link]([Link](0,3))
[Link]([Link](3,0))
//Displays "cap"
[Link]([Link](4,7))
[Link]([Link](7,4))
//Displays "Netscap"
[Link]([Link](0,7))
//Displays "Netscape"
[Link]([Link](0,8))
[Link]([Link](0,10))
Example 2. The following example replaces a substring within a string. It will replace both
individual characters and substrings. The function call at the end of the example changes the string
"Brave New World" into "Brave New Web".
function replaceString(oldS,newS,fullS) {
// Replaces oldS with newS in the string fullS
for (var i=0; i<[Link]; i++) {
if ([Link](i,i+[Link]) == oldS) {
fullS = [Link](0,i)
+newS+[Link](i+[Link],[Link])
}
}
return fullS
}
replaceString("World","Web","Brave New World")
Example 3. Using LANGUAGE="JavaScript1.2", the following script produces a runtime error (out
of memory).
<SCRIPT LANGUAGE="JavaScript1.2">
str="Netscape"
[Link]([Link](0,3);
[Link]([Link](3,0);
</SCRIPT>
Without LANGUAGE="JavaScript1.2", the above script prints
Net Net
Page No:108
In the second write, the index numbers are swapped.
See also
substr
sup
Causes a string to be displayed as a superscript, as if it were in a SUP tag.
Method of String
Syntax
sup()
Parameters
None
Description
Use the sup method with the write or writeln methods to format and display a string in a
document. In server-side JavaScript, use the write function to generate the HTML.
Examples
The following example uses the sub and sup methods to format a string:
var superText="superscript"
var subText="subscript"
[Link]("This is what a " + [Link]() + " looks like.")
[Link]("<P>This is what a " + [Link]() + " 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
[Link]
toLowerCase
Returns the calling string value converted to lowercase.
Method of String
Syntax
toLowerCase()
Parameters
None
Description
The toLowerCase method returns the value of the string converted to lowercase. toLowerCase does
not affect the value of the string itself.
Examples
Page No:109
The following example displays the lowercase string "alphabet":
var upperText="ALPHABET"
[Link]([Link]())
See also
[Link]
toUpperCase
Returns the calling string value converted to uppercase.
Method of String
Syntax
toUpperCase()
Parameters
None
Description
The toUpperCase method returns the value of the string converted to uppercase. toUpperCase does
not affect the value of the string itself.
Examples
Chapter 5
Document
This chapter deals with the document and its associated objects, document, Layer, Link, Anchor,
Area, Image, and Applet.
Object Description
Anchor A place in a document that is the target of a hypertext link.
Applet Includes a Java applet in a web page.
Area Defines an area of an image as an image map.
document Contains information on the current document, and provides methods for displaying
Page No:110
HTML output to the user.
Image An image on an HTML form.
Layer Corresponds to a layer in an HTML page and provides a means for manipulating that
layer.
Link A piece of text, an image, or an area of an image identified as a hypertext link.
Anchor
A place in a document that is the target of a hypertext link.
Client-side object
Created by
Using the HTML A tag or calling the [Link] method. The JavaScript runtime engine creates
an Anchor object corresponding to each A tag in your document that supplies the NAME attribute. It
puts these objects in an array in the [Link] property. You access an Anchor object by
indexing this array.
[Link](nameAttribute)
where:
theString A String object.
nameAttribute A string.
To define an anchor with the A tag, use standard HTML syntax. If you specify the NAME attribute, you
can use the value of that attribute to index into the anchors array.
Description
If an Anchor object is also a Link object, the object has entries in both the anchors and links arrays.
Properties
None.
Methods
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 [Link], a link in another file could define a jump to the
anchor as follows:
<A HREF="[Link]#javascript_intro">Introduction</A>
Example 2: anchors array. The following example opens two windows. The first window contains
a series of buttons that set [Link] 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, ... ([Link]-1).) When a button is pressed in the first window, the
Page No:111
onClick event handler verifies that the anchor exists before setting [Link] to the
specified anchor name.
[Link], 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("[Link]","secondLinkWindow",
"scrollbars=yes,width=250, height=400")
function linkToWindow(num) {
if ([Link] > num)
[Link]=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([Link])">
<INPUT TYPE="button" VALUE="1" NAME="link0_button"
onClick="linkToWindow([Link])">
<INPUT TYPE="button" VALUE="2" NAME="link0_button"
onClick="linkToWindow([Link])">
<INPUT TYPE="button" VALUE="3" NAME="link0_button"
onClick="linkToWindow([Link])">
<INPUT TYPE="button" VALUE="4" NAME="link0_button"
onClick="linkToWindow([Link])">
</FORM>
</BODY>
</HTML>
[Link], 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>
<UL><LI>one
<LI>two
<LI>three
<LI>four</UL>
<P><A NAME="1"><B>Some colors</B> (Anchor 1)</A>
<UL><LI>red
<LI>orange
<LI>yellow
<LI>green</UL>
<P><A NAME="2"><B>Some music types</B> (Anchor 2)</A>
<UL><LI>R&B
<LI>Jazz
<LI>Soul
<LI>Reggae
<LI>Rock</UL>
<P><A NAME="3"><B>Some countries</B> (Anchor 3)</A>
<UL><LI>Afghanistan
<LI>Brazil
<LI>Canada
<LI>Finland
<LI>India</UL>
</BODY>
</HTML>
Applet
Page No:112
Includes a Java applet in a web page.
Client-side object
Created by
The HTML APPLET tag. The JavaScript runtime engine creates an Applet object corresponding to
each applet in your document. It puts these objects in an array in the [Link] property.
You access an Applet object by indexing this array.
To define an applet, use standard HTML syntax. If you specify the NAME attribute, you can use the
value of that attribute to index into the applets array. To refer to an applet in JavaScript, you must
supply the MAYSCRIPT attribute in its definition.
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 [Link] applet
access to JavaScript on your page, specify the following:
<APPLET CODE="[Link]" WIDTH=200 HEIGHT=35
NAME="musicApp" MAYSCRIPT>
Accessing JavaScript when the MAYSCRIPT attribute is not specified results in an exception.
Property Summary
All public properties of the applet are available for JavaScript access to the Applet object.
Method Summary
Examples
Area
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. Area objects are a type of Link object.
Client-side object
document
Contains information about the current document, and provides methods for displaying HTML output
to the user.
Client-side object
Created by
The HTML BODY tag. The JavaScript runtime engine creates a document object for each HTML page.
Each Window object has a document property whose value is a document object.
Page No:113
To define a document object, use standard HTML syntax for the BODY tag with the addition of
JavaScript event handlers.
Event handlers
The onBlur, onFocus, onLoad, and onUnload event handlers are specified in the BODY tag but are
actually event handlers for the Window object. The following are event handlers for the document
object.
onClick
onDblClick
onKeyDown
onKeyPress
onKeyUp
onMouseDown
onMouseUp
Description
An HTML document consists of HEAD and BODY tags. The HEAD tag 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 clear the document pane (and remove the text, form elements, and so on so they do not
redisplay) with these statements:
[Link]();
[Link]();
[Link]();
You can omit the [Link] call if you are writing text or HTML, since write does an implicit
open of that MIME type if the document stream is closed.
You can refer to 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 and are
properties of the document object.
Do not use location as a property of the document object; use the [Link] property instead.
The [Link] property, which is a synonym for [Link], will be removed in a
future release.
Property Summary
Page No:114
linkColor A string that specifies the LINK attribute.
links An array containing an entry for each link in the document.
plugins An array containing an entry for each plug-in in the document.
referrer A string that specifies the URL of the calling document.
title A string that specifies the contents of the TITLE tag.
URL A string that specifies the complete URL of a document.
vlinkColor A string that specifies the VLINK attribute.
Method Summary
captureEvents Sets the document to capture all events of the specified type.
close Closes an output stream and forces data to display.
getSelection Returns a string containing the text of the current selection.
handleEvent Invokes the handler for the specified event.
open Opens a stream to collect the output of write or writeln methods.
releaseEvents Sets the window or document to release captured events of the
specified type, sending the event to objects further along the event hierarchy.
routeEvent Passes a captured event along the normal event hierarchy.
write Writes one or more HTML expressions to a document in the specified window.
writeln Writes one or more HTML expressions to a document in the specified window and
follows them with a newline character.
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.
<HTML>
<HEAD>
<TITLE>Document object example</TITLE>
</HEAD>
<FRAMESET COLS="30%,70%">
<FRAME SRC="[Link]" NAME="frame1">
<FRAME SRC="[Link]" NAME="frame2">
</FRAMESET>
</HTML>
[Link], 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="[Link]#numbers" TARGET="frame2">Numbers</A>
<LI><A HREF="[Link]#colors" TARGET="frame2">Colors</A>
<LI><A HREF="[Link]#musicTypes" TARGET="frame2">Music types</A>
<LI><A HREF="[Link]#countries" TARGET="frame2">Countries</A>
</BODY>
</HTML>
[Link], 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>
<UL><LI>one
Page No:115
<LI>two
<LI>three
<LI>four</UL>
<P><A NAME="colors"><B>Some colors</B></A>
<UL><LI>red
<LI>orange
<LI>yellow
<LI>green</UL>
<P><A NAME="musicTypes"><B>Some music types</B></A>
<UL><LI>R&B
<LI>Jazz
<LI>Soul
<LI>Reggae</UL>
<P><A NAME="countries"><B>Some countries</B></A>
<UL><LI>Afghanistan
<LI>Brazil
<LI>Canada
<LI>Finland</UL>
</BODY>
</HTML>
See also
Frame, Window
Properties
alinkColor
A string specifying the color of an active link (after mouse-button down, but before mouse-button
up).
Property of document
Description
The alinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in Appendix B, "Color Values," in the JavaScript Guide 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 using a string literal:
[Link]="aqua"
The following example sets the color of active links to aqua using a hexadecimal triplet:
[Link]="00FFFF"
See also
anchors
An array of objects corresponding to named anchors in source order.
Property of document
Read-only
Description
Page No:116
You can refer to 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; these entries are in source order. For
example, if a document contains three named anchors whose NAME attributes are anchor1, anchor2,
and anchor3, you can refer to the anchors either as:
[Link]["anchor1"]
[Link]["anchor2"]
[Link]["anchor3"]
or as:
[Link][0]
[Link][1]
[Link][2]
To obtain the number of anchors in a document, use the length property:
[Link]. 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 [Link].
applets
An array of objects corresponding to the applets in a document in source order.
Property of document
Read-only
Description
You can refer to the applets in your code by using the applets array. This array contains an entry for
each Applet object (APPLET tag) in a document; these entries are in source order. For example, if a
document contains three applets whose NAME attributes are app1, app2, and app3, you can refer to the
anchors either as:
[Link]["app1"]
[Link]["app2"]
[Link]["app3"]
or as:
[Link][0]
[Link][1]
[Link][2]
bgColor
A string specifying the color of the document background.
Property of document
Description
The bgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals. 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 with the preferences dialog box.
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:
[Link]="aqua"
The following example sets the color of the document background to aqua using a hexadecimal
triplet:
[Link]="00FFFF"
See also
Page No:117
[Link], [Link], [Link], [Link]
cookie
String value representing all of the cookies associated with this document.
Property of document
Description
A cookie is a small piece of information stored by the web browser in the [Link] file. Use
string methods such as substring, charAt, indexOf, and lastIndexOf to determine the value
stored in the cookie.
The "expires=" component in the cookie file sets an expiration date for the cookie, so it persists
beyond the current browser session. This date string is formatted as follows:
Wdy is a string representing the full name of the day of the week.
DD is an integer representing the day of the month.
Mon is a string representing the three-character abbreviation of the month.
YY is an integer representing the last two digits of the year.
HH, MM, and SS are 2-digit representations of hours, minutes, and seconds, respectively.
Examples
The following function uses the cookie property to record a reminder for users of an application. The
cookie expiration date is set to one day after the date of the reminder.
function RecordReminder(time, expression) {
// Record a cookie of the form "@<T>=<E>" to map
// from <T> in milliseconds since the epoch,
// returned by [Link](), onto an encoded expression,
// <E> (encoded to contain no white space, semicolon,
// or comma characters)
[Link] = "@" + time + "=" + expression + ";"
// set the cookie expiration time to one day
// beyond the reminder time
[Link] += "expires=" + cookieDate(time + 24*60*60*1000)
// cookieDate is a function that formats the date
//according to the cookie spec
}
See also
Hidden
domain
Specifies the domain name of the server that served a document.
Property of document
Page No:118
.
Description
Navigator 3.0: The domain property lets scripts on multiple servers share properties when data
tainting is not enabled. With tainting disabled, a script running in one window can read properties of
another window only if both windows come from the same Web server. But large Web sites with
multiple servers might need to share properties among servers. For example, a script on the host
[Link] might need to share properties with a script on the host
[Link].
If scripts on two different servers change their domain property so that both scripts have the same
domain name, both scripts can share properties. For example, a script loaded from
[Link] could set its domain property to "[Link]". A script from
[Link] running in another window could also set its domain property to
"[Link]". Then, since both scripts have the domain "[Link]", these two
scripts can share properties, even though they did not originate from the same server.
You can change domain only in a restricted way. Initially, domain contains the hostname of the Web
server from which the document was loaded. You can set domain only to a domain suffix of itself.
For example, a script from [Link] can't set its domain property to
"[Link]". And a script from [Link] cannot set its domain to
"[Link]".
Once you change the domain property, you cannot change it back to its original value. For example,
if you change domain from "[Link]" to "[Link]", you cannot
reset it to "[Link]".
Examples
The following statement changes the domain property to "[Link]". This statement is
valid only if "[Link]" is a suffix of the current domain, such as
"[Link]".
[Link]="[Link]"
embeds
An array containing an entry for each object embedded in the document.
Property of document
Read-only
Description
You can refer to embedded objects (created with the EMBED tag) in your code by using the embeds
array. This array contains an entry for each EMBED tag in a document in source order. For example, if
a document contains three embedded objects whose NAME attributes are e1, e2, and e3, you can refer
to the objects either as:
[Link]["e1"]
[Link]["e2"]
[Link]["e3"]
or as:
[Link][0]
[Link][1]
[Link][2]
Elements in the embeds array may have public callable functions, if they refer to a plug-in that uses
LiveConnect. See the JavaScript Guide.
Use the elements in the embeds array to interact with the plug-in that is displaying the embedded
object. If a plug-in is not Java-enabled, you cannot do anything with its element in the embeds array.
Page No:119
The fields and methods of the elements in the embeds array vary from plug-in to plug-in; see the
documentation supplied by the plug-in manufacturer.
When you use the EMBED tag to generate output from a plug-in application, you are not creating a
Plugin object.
Examples
See also
Plugin
fgColor
A string specifying the color of the document (foreground) text.
Property of document
Description
The fgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed
in Appendix B, "Color Values," in the JavaScript Guide. 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 with the
preferences dialog box 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:
formName
Property of document
The document object contains a separate property for each form in the document. The name of this
property is the value of its NAME attribute. See Form for information on Form objects. You cannot add
new forms to the document by creating new properties, but you can modify the form by modifying
this object.
forms
An array containing an entry for each form in the document.
Property of document
Read-only
.
Description
You can refer to 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; these entries are in source
order. For example, if a document contains three forms whose NAME attributes are form1, form2, and
form3, you can refer to the objects in the forms array either as:
Page No:120
[Link]["form1"]
[Link]["form2"]
[Link]["form3"]
or as:
[Link][0]
[Link][1]
[Link][2]
Additionally, the document object has a separate property for each named form, so you could refer to
these forms also as:
document.form1
document.form2
document.form3
For example, you would refer to a Text object named quantity in the second form as
[Link][1].quantity. You would refer to the value property of this Text object as
[Link][1].[Link].
The value of each element in the forms array is <object nameAttribute>, where nameAttribute
is the NAME attribute of the form.
images
An array containing an entry for each image in the document.
Property of document
Read-only
You can refer to the images in a document by using the images array. This array contains an entry for
each Image object (IMG tag) in a document; the entries are in source order. Images created with the
Image constructor are not included in the images array. For example, if a document contains three
images whose NAME attributes are im1, im2, and im3, you can refer to the objects in the images array
either as:
[Link]["im1"]
[Link]["im2"]
[Link]["im3"]
or as:
[Link][0]
[Link][1]
[Link][2]
lastModified
A string representing the date that a document was last modified.
Property of document
Read-only
Description
The lastModified property is derived from the HTTP header data sent by the web server. Servers
generally obtain this date by examining the file's modification date.
The last modified date is not a required portion of the header, and some servers do not supply it. If
the server does not return the last modified information, JavaScript receives a 0, which it displays as
January 1, 1970 GMT. The following code checks the date returned by lastModified and prints out
a value that corresponds to unknown.
Page No:121
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:
[Link]("This page updated on " + [Link])
layers
The layers property is an array containing an entry for each layer within the document.
Property of document
Description
You can refer to the layers in your code by using the layers array. This array contains an entry for
each Layer object (LAYER or ILAYER tag) in a document; these entries are in source order. For
example, if a document contains three layers whose NAME attributes are layer1, layer2, and layer3,
you can refer to the objects in the layers array either as:
[Link]["layer1"]
[Link]["layer2"]
[Link]["layer3"]
or as:
[Link][0]
[Link][1]
[Link][2]
When accessed by integer index, array elements appear in z-order from back to front, where 0 is the
bottommost layer and higher layers are indexed by consecutive integers. The index of a layer is not
the same as its zIndex property, as the latter does not necessarily enumerate layers with consecutive
integers. Adjacent layers can have the same zIndex property values.
[Link]
[Link][index]
[Link]["layerName"]
// example of using layers property to access nested layers:
[Link]["parentlayer"].layers["childlayer"]
Elements of a layers array are JavaScript objects that cannot be set by assignment, though their
properties can be set. For example, the statement
[Link][0]="music"
is invalid (and ignored) because it attempts to alter the layers array. However, the properties of the
objects in the array readable and some are writable. For example, the statement
[Link]["suspect1"].left = 100;
is valid. This sets the layer's horizontal position to 100. The following example sets the background
color to blue for the layer bluehouse which is nested in the layer houses.
[Link]["houses"].layers["bluehouse"].bgColor="blue";
linkColor
A string specifying the color of the document hyperlinks.
Property of document
Description
The linkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in the JavaScript Guide. 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 with the preferences dialog box. 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".
Page No:122
Examples
The following example sets the color of document links to aqua using a string literal:
[Link]="aqua"
The following example sets the color of document links to aqua using a hexadecimal triplet:
[Link]="00FFFF"
See also
links
An array of objects corresponding to Area and Link objects in source order.
Property of document
Read-only
Description
You can refer to the Area and Link objects in your code by using the links array. This array
contains an entry for each Area (<AREA HREF="..."> tag) and Link (<A HREF="..."> tag) object in
a document in source order. It also contains links created with the link method. For example, if a
document contains three links, you can refer to them as:
[Link][0]
[Link][1]
[Link][2]
plugins
An array of objects corresponding to Plugin objects in source order.
Property of document
Read-only
You can refer to the Plugin objects in your code by using the plugins array. This array contains an
entry for each Plugin object in a document in source order. For example, if a document contains
three plugins, you can refer to them as:
[Link][0]
[Link][1]
[Link][2]
referrer
Specifies the URL of the calling document when a user clicks a link.
Property of document
Read-only
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.
referrer is empty if the user typed a URL in the Location box, or used some other means to get to
the current URL. referrer is also empty if the server does not provide environment variable
information.
Examples
Page No:123
In the following example, the getReferrer function is called from the destination document. It
returns the URL of the source document.
function getReferrer() {
return [Link]
}
title
A string representing the title of a document.
Property of document
Read-only
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The title property is a reflection of the value specified between the TITLE start and end tags. If a
document does not have a title, the title property is null.
Examples
In the following example, the value of the title property is assigned to a variable called docTitle:
var newWindow = [Link]("[Link]
var docTitle = [Link]
URL
A string specifying the complete URL of the document.
Property of document
Read-only
Description
URL is a string-valued property containing the full URL of the document. It usually matches what
[Link] is set to when you load the document, but redirection may change
[Link].
Examples
See also
[Link]
vlinkColor
A string specifying the color of visited links.
Property of document
Description
The vlinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals
listed in the JavaScript Guide. This property is the JavaScript reflection of the VLINK attribute of the
Page No:124
BODY tag. The default value of this property is set by the user with the preferences dialog box. 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:
[Link]="aqua"
The following example sets the color of active links to aqua using a hexadecimal triplet:
[Link]="00FFFF"
See also
Methods
captureEvents
Sets the document to capture all events of the specified type.
Method of document
Syntax
captureEvents(eventType)
Parameters
eventType The type of event to be captured. The available event types are listed with the event
object.
Description
When a window with frames wants to capture events in pages loaded from different locations
(servers), you need to use [Link] in a signed script and precede it with
[Link]. For more information and an example, see
[Link].
captureEvents works in tandem with releaseEvents, routeEvent, and handleEvent. For more
information, see "Events in Navigator 4.0".
close
Closes an output stream and forces data sent to layout to display.
Method of document
Syntax
close()
Parameters
None.
Page No:125
Description
The close method closes a stream opened with the [Link] 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 [Link] to close a stream that was opened with
[Link]. The [Link] method forces the content of the stream to display in the
window.
function windowWriter1() {
var myString = "Hello, world!"
[Link]()
[Link](myString + "<P>")
[Link]()
}
See also
getSelection
Returns a string containing the text of the current selection.
Method of document
Syntax
getSelection()
Description
Security
Examples
If you have a form with the following code and you click on the button, JavaScript displays an alert
box containing the currently selected text from the window containing the button:
<INPUT TYPE="BUTTON" NAME="getstring"
VALUE="Show highlighted text (if any)"
onClick="alert('You have selected:\n'+[Link]());">
handleEvent
Invokes the handler for the specified event.
Method of document
Syntax
handleEvent(event)
Parameters
Page No:126
event The name of an event for which the specified object has an event handler.
Description
open
Opens a stream to collect the output of write or writeln methods.
Method of document
Syntax
open(mimeType, replace)
Parameters
mimeType(Optional) A string specifying the type of document to which you are writing. If you do
not specify mimeType, text/html is the default.
replace (Optional) The string "replace". If you supply this parameter, mimeType must be
"text/html". Causes the new document to reuse the history entry that the previous
document used.
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 [Link] method. The close method causes text or images that
were sent to layout to display. After using [Link], call [Link] again when you
want to begin another output stream.
The "replace" keyword causes the new document to reuse the history entry that the previous
document used. When you specify "replace" while opening a document, the target window's history
length is not incremented even after you write and close.
"replace" is typically used on a window that has a blank document or an "about:blank" URL.
After "replace" is specified, the write method typically generates HTML for the window, replacing
the history entry for the blank URL. Take care when using generated HTML on a window with a
Page No:127
blank URL. If you do not specify "replace", the generated HTML has its own history entry, and the
user can press the Back button and back up until the frame is empty.
Examples
Example 1. The following function calls [Link] to open a stream before issuing a write
method:
function windowWriter1() {
var myString = "Hello, world!"
[Link]()
[Link]("<P>" + myString)
[Link]()
}
Example 2. The following function calls [Link] with the "replace" keyword to open a
stream before issuing write methods. The HTML code in the write methods is written to
msgWindow, replacing the current history entry. The history length of msgWindow is not incremented.
function windowWriter2() {
var myString = "Hello, world!"
[Link]("text/html","replace")
[Link]("<P>" + myString)
[Link]("<P>[Link] is " +
[Link])
[Link]()
}
The following code creates the msgWindow window and calls the function:
msgWindow=[Link]('','',
'toolbar=yes,scrollbars=yes,width=400,height=300')
windowWriter2()
Example 3. 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 = [Link]("", "teensy", "width=1,height=1")
if (tiny != null) {
if ([Link](mimeType) != null)
havePlugIn = true
[Link]()
}
return havePlugIn
}
var haveShockwavePlugIn = probePlugIn("application/x-director")
See also
releaseEvents
Sets the document to release captured events of the specified type, sending the event to objects
further along the event hierarchy.
Method of document
Note
If the original target of the event is a window, the window receives the event even if it is set to
release that type of event.
Syntax
releaseEvents(eventType)
Page No:128
Parameters
Description
releaseEvents works in tandem with captureEvents, routeEvent, and handleEvent. For more
information, see "Events in Navigator 4.0".
routeEvent
Passes a captured event along the normal event hierarchy.
Method of document
Syntax
routeEvent(event)
Parameters
Description
If a subobject (document or layer) is also capturing the event, the event is sent to that object.
Otherwise, it is sent to its original target.
routeEvent works in tandem with captureEvents, releaseEvents, and handleEvent. For more
information, see "Events in Navigator 4.0".
write
Writes one or more HTML expressions to a document in the specified window.
Method of document
Syntax
[Link](expr1, ...,exprN)
Parameters
Description
The write method displays any number of expressions in the document window. You can specify
any JavaScript expression with the write method, including numeric, string, or logical expressions.
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 implicitly opens a new document of
mimeType text/html if you do not explicitly issue a [Link] method in the event handler.
You can use the write method to generate HTML and JavaScript code. However, the HTML parser
reads the generated code as it is being written, so you might have to escape some characters. For
example, the following write method generates a comment and writes it to window2:
Page No:129
window2=[Link]('','window2')
beginComment="\<!--"
endComment="--\>"
[Link](beginComment)
[Link](" This some text inside a comment. ")
[Link](endComment)
In Navigator 3.0 and later, users can print and save generated HTML using the commands on the File
menu.
If you choose Document Source or Frame Source from the View menu, the web browser displays the
content of the HTML file with the generated HTML. (This is what would be displayed using a
wysiwyg: URL.)
If you instead want to view the HTML source showing the scripts which generate HTML (with the
[Link] and [Link] methods), do not use the Document Source or Frame
Source menu item. In this situation, use the view-source: protocol.
<HTML>
<BODY>
Hello,
<SCRIPT>[Link](" there.")</SCRIPT>
</BODY>
</HTML>
If you load this URL into the web browser, it displays the following:
Hello, there.
If you choose View Document Source, the browser displays:
<HTML>
<BODY>
Hello,
there.
</BODY>
</HTML>
If you load view-source:[Link] the browser displays:
<HTML>
<BODY>
Hello,
<SCRIPT>[Link](" there.")</SCRIPT>
</BODY>
</HTML>
For information on specifying the view-source: protocol in the location object, see the Location
object.
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
[Link]("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...
[Link](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."
[Link](status = (age >= 18) ? "Adult" : "Minor")
See also
Page No:130
[Link], [Link], [Link]
writeln
Writes one or more HTML expressions to a document in the specified window and follows them with
a newline character.
Method of document
Syntax
Parameters
Description
The writeln method displays any number of expressions in a document window. You can specify
any JavaScript expression, including numeric, string, or logical expressions.
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 the PRE tag.
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 [Link] method in the event handler.
Examples
All the examples used for the write method are also valid with the writeln method.
Image
An image on an HTML form.
Client-side object
Created by
The JavaScript runtime engine creates an Image object corresponding to each IMG tag in your
document. It puts these objects in an array in the [Link] property. You access an Image
object by indexing this array.
To define an image with the IMG tag, use standard HTML syntax with the addition of JavaScript
event handlers. If specify a value for the NAME attribute, you can use that name when indexing the
images array.
Parameters
Page No:131
width (Optional) The image width, in pixels.
height (Optional) The image height, in pixels.
Event handlers
onAbort
onError
onKeyDown
onKeyPress
onKeyUp
onLoad
To define an event handler for an Image object created with the Image constructor, set the appropriate
property of the object. For example, if you have an Image object named imageName and you want to
set one of its event handlers to a function whose name is handlerFunction, use one of the following
statements:
[Link] = handlerFunction
[Link] = handlerFunction
[Link] = handlerFunction
[Link] = handlerFunction
[Link] = handlerFunction
[Link] = handlerFunction
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 Link.
Description
The position and size of an image in a document are set when the document is displayed in the web
browser and cannot be changed using JavaScript (the width and height properties are read-only for
these objects). You can change which image is displayed by setting the src and lowsrc properties.
(See the descriptions of [Link] and [Link].)
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).
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, you can set the src property of the displayed image to the same
value as that used for the previously fetched image, as follows.
Property Summary
Page No:132
prototype Allows the addition of properties to an Image object.
src Reflects the SRC attribute.
vspace Reflects the VSPACE attribute.
width Reflects the WIDTH attribute.
Method Summary
Examples
Example 1: Create an image with the IMG tag. The following code defines an image using the IMG
tag:
<IMG NAME="aircraft" SRC="[Link]" ALIGN="left" VSPACE="10">
The following code refers to the image:
[Link]='[Link]'
When you refer to an image by its name, you must include the form name if the image is on a form.
The following code refers to the image if it is on a form:
[Link]='[Link]'
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, [Link], does
not have dimensions of 70x50 pixels, it is scaled to that size.
myImage = new Image(70, 50)
[Link] = "[Link]"
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()
[Link] = "[Link]"
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 preloaded 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(idx=0; idx < 9; idx++) {
shirtImg[idx] = new Image()
shirtImg[idx].src = "shirt-" + shirts[idx] + ".gif"
}
function changeShirt(form)
{
shirtColor = [Link][[Link]].text
shirtSize = [Link][[Link]].text
newSrc = "shirt-" + [Link](0) + "-" + [Link](0) + ".gif"
[Link] = newSrc
}
function allShirts()
{
[Link] = shirtImg[doneThis].src
doneThis++
if(doneThis != 9)setTimeout("allShirts()", 500)
else doneThis = 0
return
}
Page No:133
</SCRIPT>
<FONT SIZE=+2><B>Netscape Polo Shirts!</FONT></B>
<TABLE CELLSPACING=20 BORDER=0>
<TR>
<TD><IMG name="shirt" SRC="[Link]"></TD>
<TD>
<FORM>
<B>Color</B>
<SELECT SIZE=3 NAME="color" onChange="changeShirt([Link])">
<OPTION> Red
<OPTION SELECTED> White
<OPTION> Blue
</SELECT>
<P>
<B>Size</B>
<SELECT SIZE=3 NAME="size" onChange="changeShirt([Link])">
<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 10 images that make up the animation ([Link], [Link], [Link], and
so on). When the Image object is placed on the document with the IMG tag, [Link] 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() {
[Link] = theImages[imageNum].src
imageNum++
if(imageNum > 10) {
imageNum = 1
}
}
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="[Link]" 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
Page No:134
Link, onClick, onMouseOut, onMouseOver
Properties
border
A string specifying the width, in pixels, of an image border.
Property of Image
Read-only
Description
The border property reflects the BORDER attribute of the IMG tag. For images created with the Image
constructor, the value of the border property is 0.
Examples
The following function displays the value of an image's border property if the value is not 0.
function checkBorder(theImage) {
if ([Link]==0) {
alert('The image has no border!')
}
else alert('The image's border is ' + [Link])
}
See also
complete
A boolean value that indicates whether the web browser has completed its attempt to load an image.
Property of Image
Read-only
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="[Link][0].src='[Link]'">F-15 Eagle
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="[Link][0].src='[Link]'">F-15 Eagle 2
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="[Link][0].src='[Link]'">AH-64 Apache
<BR><INPUT TYPE="button" VALUE="Is the image completely loaded?"
onClick="alert('The value of the complete property is '
+ [Link][0].complete)">
<BR>
<IMG NAME="aircraft" SRC="[Link]" ALIGN="left" VSPACE="10"><BR>
See also
[Link], [Link]
height
A string specifying the height of an image in pixels.
Page No:135
Property of Image
Read-only
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.
Examples
The following function displays the values of an image's height, width, hspace, and vspace
properties.
function showImageSize(theImage) {
alert('height=' + [Link]+
'; width=' + [Link] +
'; hspace=' + [Link] +
'; vspace=' + [Link])
}
See also
hspace
A string specifying a margin in pixels between the left and right edges of an image and the
surrounding text.
Property of Image
Read-only
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.
Examples
See also
lowsrc
A string specifying the URL of a low-resolution version of an image to be displayed in a document.
Property of Image
Description
The lowsrc property initially reflects the LOWSRC attribute of the IMG tag. The web browser 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 also
Page No:136
[Link], [Link]
name
A string specifying the name of an object.
Property of Image
Read-only
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
Represents the value of the NAME attribute. For images created with the Image constructor, the value
of the name property is null.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][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=[Link]("[Link]
alert([Link])
prototype
Represents the prototype for this class. You can use the prototype to add properties or methods to all
instances of a class. For more information, see [Link].
Property of Image
src
A string specifying the URL of an image to be displayed in a document.
Property of Image
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 refers to an image that is not the same size as the image cell it is
loaded into, the source image is scaled to fit.
Page No:137
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 [Link]:
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) {
[Link][0].lowsrc=lowRes
[Link][0].src=highRes
}
</SCRIPT>
<FORM NAME="imageForm">
<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="displayImage('[Link]','[Link]')">F-15 Eagle
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="displayImage('[Link]','[Link]')">F-15 Eagle 2
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="displayImage('[Link]','[Link]')">AH-64 Apache
<BR>
<IMG NAME="aircraft" SRC="[Link]" LOWSRC="[Link]" ALIGN="left"
VSPACE="10"><BR>
</FORM>
See also
[Link], [Link]
vspace
A string specifying a margin in pixels between the top and bottom edges of an image and the
surrounding text.
Property of Image
Read-only
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.
Examples
See also
width
A string specifying the width of an image in pixels.
Page No:138
Property of Image
Read-only
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.
Examples
See also
Methods
handleEvent
Invokes the handler for the specified event.
Method of Image
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
Layer
Corresponds to a layer in an HTML page and provides a means for manipulating that layer.
Client-side object
Created by
The HTML LAYER or ILAYER tag, or using cascading style sheet syntax. The JavaScript runtime
engine creates a Layer object corresponding to each layer in your document. It puts these objects in
an array in the [Link] property. You access a Layer object by indexing this array.
To define a layer, use standard HTML syntax. If you specify the ID attribute, you can use the value of
that attribute to index into the layers array.
Some layer properties can be directly modified by assignment; for example, "[Link]
= hide". A layer object also has methods that can affect these properties.
Event handlers
onMouseOver
onMouseOut
onLoad
onFocus
onBlur
Page No:139
Property Summary
above The layer object above this one in z-order, among all layers in the document or the
enclosing window object if this layer is topmost.
background The image to use as the background for the layer's canvas.
bgColor The color to use as a solid background color for the layer's canvas.
below The layer object below this one in z-order, among all layers in the document or null
if this layer is at the bottom.
[Link] The bottom edge of the clipping rectangle (the part of the layer that is visible.)
[Link] The height of the clipping rectangle (the part of the layer that is visible.)
[Link] The left edge of the clipping rectangle (the part of the layer that is visible.)
[Link] The right edge of the clipping rectangle (the part of the layer that is visible.)
[Link] The top edge of the clipping rectangle (the part of the layer that is visible.)
[Link] The width of the clipping rectangle (the part of the layer that is visible.)
document The layer's associated document.
left The horizontal position of the layer's left edge, in pixels, relative to the origin of its
parent layer.
name A string specifying the name assigned to the layer through the ID attribute in the
LAYER tag.
pageX The horizontal position of the layer, in pixels, relative to the page.
page y The vertical position of the layer, in pixels, relative to the page.
parentLayer The layer object that contains this layer, or the enclosing window object if this layer
is not nested in another layer.
siblingAbove The layer object above this one in z-order, among all layers that share the same
parent layer, or null if the layer has no sibling above.
siblingBelow The layer object below this one in z-order, among all layers that share the same
parent layer, or null if layer is at the bottom.
src A string specifying the URL of the layer's content.
top The vertical position of the layer's top edge, in pixels, relative to the origin of its
parent layer.
visibility Whether or not the layer is visible.
zIndex The relative z-order of this layer with respect to its siblings.
Method Summary
captureEvents Sets the window or document to capture all events of the specified type.
handleEvent Invokes the handler for the specified event.
load Changes the source of a layer to the contents of the specified file, and
simultaneously changes the width at which the layer's HTML contents will be
wrapped.
moveAbove Stacks this layer above the layer specified in the argument, without changing either
layer's horizontal or vertical position.
moveBelow Stacks this layer below the specified layer, without changing either layer's
horizontal or vertical position.
moveBy Changes the layer position by applying the specified deltas, measured in pixels.
moveTo Moves the top-left corner of the window to the specified screen coordinates.
moveToAbsolute Changes the layer position to the specified pixel coordinates within the page
(instead of the containing layer.)
releaseEvents Sets the layer to release captured events of the specified type, sending the event to
objects further along the event hierarchy.
resizeBy Resizes the layer by the specified height and width values (in pixels).
resizeTo Resizes the layer to have the specified height and width values (in pixels).
routeEvent Passes a captured event along the normal event hierarchy.
Note
Page No:140
Just as in the case of a document, if you want to define mouse click response for a layer, you must
capture onMouseDown and onMouseUp events at the level of the layer and process them as you want.
See "Events in Navigator 4.0" for more details about capturing events.
If an event occurs in a point where multiple layers overlap, the topmost layer gets the event, even if it
is transparent. However, if a layer is hidden, it does not get events.
Properties
above
The layer object above this one in z-order, among all layers in the document or the enclosing
window object if this layer is topmost.
Property of Layer
Read-only
background
The image to use as the background for the layer's canvas (which is the part of the layer within the
clip rectangle).
Property of Layer
Description
Each layer has a background property, whose value is an image object, whose src attribute is a URL
that indicates the image to use to provide a tiled backdrop. The value is null if the layer has no
backdrop. For example:
[Link] = "[Link]";
bgColor
A string specifying the color to use as a solid background color for the layer's canvas (the part of the
layer within the clip rectangle).
Property of Layer
Description
The bgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed
in the JavaScript Guide. This property is the JavaScript reflection of the BGCOLOR attribute of the
BODY tag.
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 background color of the myLayer layer's canvas to aqua using a string
literal:
[Link]="aqua"
The following example sets the background color of the myLayer layer's canvas to aqua using a
hexadecimal triplet:
[Link]="00FFFF"
See also
Page No:141
[Link]
below
The layer object below this one in z-order, among all layers in the document or null if this layer is at
the bottom.
Property of Layer
Read-only
[Link]
The bottom edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer
that is outside the clipping rectangle is not displayed.
Property of Layer
[Link]
The height of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is
outside the clipping rectangle is not displayed.
Property of Layer
[Link]
The left edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is
outside the clipping rectangle is not displayed.
Property of Layer
[Link]
The right edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that
is outside the clipping rectangle is not displayed.
Property of Layer
[Link]
The top edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is
outside the clipping rectangle is not displayed.
Property of Layer
[Link]
The width of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is
outside the clipping rectangle is not displayed.
Property of Layer
document
The layer's associated document.
Property of Layer
Read-only
Description
Page No:142
Each layer object contains its own document object. This object can be used to access the images,
applets, embeds, links, anchors and layers that are contained within the layer. Methods of the
document object can also be invoked to change the contents of the layer.
left
The horizontal position of the layer's left edge, in pixels, relative to the origin of its parent layer.
Property of Layer
name
A string specifying the name assigned to the layer through the ID attribute in the LAYER tag.
Property of Layer
Read-only
pageX
The horizontal position of the layer, in pixels, relative to the page.
Property of Layer
pageY
The vertical position of the layer, in pixels, relative to the page.
Property of Layer
parentLayer
The layer object that contains this layer, or the enclosing window object if this layer is not nested in
another layer.
Property of Layer
Read-only
siblingAbove
The layer object above this one in z-order, among all layers that share the same parent layer or null if
the layer has no sibling above.
Property of Layer
Read-only
siblingBelow
The layer object below this one in z-order, among all layers that share the same parent layer or null
if layer is at the bottom.
Property of Layer
Read-only
src
A URL string specifying the source of the layer's content. Corresponds to the SRC attribute.
Property of Layer
top
Page No:143
The top property is a synonym for the topmost Navigator window, which is a document window or
web browser window.
Property of Layer
Read-only
Description
The top property refers to the topmost window that contains frames or nested framesets. Use the top
property to refer to this ancestor window.
<object objectReference>
where objectReference is an internal reference.
Examples
The statement [Link] specifies the number of frames contained within the topmost ancestor
window. When the topmost ancestor is defined as follows, [Link] returns three:
<FRAMESET COLS="30%,40%,30%">
<FRAME SRC=[Link] NAME="childFrame1">
<FRAME SRC=[Link] NAME="childFrame2">
<FRAME SRC=[Link] NAME="childFrame3">
</FRAMESET>
visibility
Whether or not the layer is visible.
Property of Layer
Description
A value of show means show the layer; hide means hide the layer; inherit means inherit the
visibility of the parent layer.
zIndex
The relative z-order of this layer with respect to its siblings.
Method of Layer
Description
Sibling layers with lower numbered z-indexes are stacked underneath this layer. The value of zIndex
must be 0 or a positive integer.
Methods
captureEvents
Sets the window or document to capture all events of the specified type.
Method of Layer
Syntax
captureEvents(eventType)
Page No:144
Parameters
eventType Type of event to be captured. Available event types are listed with event.
Description
When a window with frames wants to capture events in pages loaded from different locations
(servers), you need to use captureEvents in a signed script and precede it with
enableExternalCapture. For more information and an example, see enableExternalCapture.
captureEvents works in tandem with releaseEvents, routeEvent, and handleEvent. For more
information, see "Events in Navigator 4.0".
handleEvent
Invokes the handler for the specified event.
Method of Layer
Syntax
handleEvent(event)
Parameters
event Name of an event for which the specified object has an event handler.
Description
handleEvent works in tandem with captureEvents, releaseEvents, and routeEvent. For more
information, see "Events in Navigator 4.0".
load
Changes the source of a layer to the contents of the specified file and simultaneously changes the
width at which the layer's HTML contents are wrapped.
Method of Layer
Syntax
load(sourcestring, width)
Parameters
moveAbove
Stacks this layer above the layer specified in the argument, without changing either layer's horizontal
or vertical position. After re-stacking, both layers will share the same parent layer.
Method of Layer
Syntax
moveAbove(aLayer)
Parameters
Page No:145
aLayer The layer above which to move the current layer.
moveBelow
Stacks this layer below the specified layer, without changing either layer's horizontal or vertical
position. After re-stacking, both layers will share the same parent layer.
Method of Layer
Syntax
moveBelow(aLayer)
Parameters
moveBy
Changes the layer position by applying the specified deltas, measured in pixels.
Method of Layer
Syntax
moveBy(horizontal, vertical)
Parameters
moveTo
Moves the top-left corner of the window to the specified screen coordinates.
Method of Layer
Syntax
moveTo(x-coordinate, y-coordinate)
Parameters
x-coordinate An integer representing the top edge of the window in screen coordinates.
y-coordinate An integer representing the left edge of the window in screen coordinates.
Security
To move a window offscreen, call the moveTo method in a signed script. For information on security
in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript Guide.
Description
Changes the layer position to the specified pixel coordinates within the containing layer. For ILayers,
moves the layer relative to the natural inflow position of the layer.
See also
[Link]
Page No:146
moveToAbsolute
Changes the layer position to the specified pixel coordinates within the page (instead of the
containing layer.)
Method of Layer
Syntax
moveToAbsolute(x, y)
Parameters
Description
This method is equivalent to setting both the pageX and pageY properties of the layer object.
releaseEvents
Sets the window or document to release captured events of the specified type, sending the event to
objects further along the event hierarchy.
Method of Layer
Syntax
releaseEvents(eventType)
Parameters
Description
If the original target of the event is a window, the window receives the event even if it is set to
release that type of event. releaseEvents works in tandem with captureEvents, routeEvent, and
handleEvent. For more information, see "Events in Navigator 4.0".
resizeBy
Resizes the layer by the specified height and width values (in pixels).
Method of Layer
Syntax
resizeBy(width, height)
Parameters
Description
This does not layout any HTML contained in the layer again. Instead, the layer contents may be
clipped by the new boundaries of the layer. This method has the same effect as adding width and
height to [Link] and [Link].
Page No:147
resizeTo
Resizes the layer to have the specified height and width values (in pixels).
Method of Layer
Description
This does not layout any HTML contained in the layer again. Instead, the layer contents may be
clipped by the new boundaries of the layer.
Syntax
resizeBy(width, height)
Parameters
Description
This method has the same effect setting [Link] and [Link].
routeEvent
Passes a captured event along the normal event hierarchy.
Method of Layer
Syntax
routeEvent(event)
Parameters
Description
If a subobject (document or layer) is also capturing the event, the event is sent to that object.
Otherwise, it is sent to its original target.
Link
A piece of text, an image, or an area of an image identified as a hypertext link. When the user clicks
the link text, image, or area, the link hypertext reference is loaded into its target window. Area
objects are a type of Link object.
Client-side object
Created by
By using the HTML A or AREA tag or by a call to the [Link] method. The JavaScript runtime
engine creates a Link object corresponding to each A and AREA tag in your document that supplies the
HREF attribute. It puts these objects as an array in the [Link] property. You access a Link
object by indexing this array.
Page No:148
To define a link with the [Link] method:
[Link](hrefAttribute)
where:
theString A String object.
hrefAttribute Any string that specifies the HREF attribute of the A tag; it should be a valid URL
(relative or absolute).
To define a link with the A or MAP tag, use standard HTML syntax with the addition of JavaScript
event handlers. If you're going to use the onMouseOut or onMouseOver event handlers, you must
supply a value for the HREF attribute.
Event handlers
onDblClick
onMouseOut
onMouseOver
onClick
onDblClick
onKeyDown
onKeyPress
onKeyUp
onMouseDown
onMouseOut
onMouseUp
onMouseOver
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.
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 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\[Link]" ALIGN="top" HEIGHT="50" WIDTH="50">
</A>
Page No:149
Property Summary
Method Summary
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
[Link] in the window window2. If window2 does not exist, it is created.
<LI><A HREF=[Link]#numbers TARGET="window2">Numbers</A>
Example 3. The following example takes the user back x entries in the history list:
<A HREF="javascript:[Link](-1 * x)">Click here</A>
Example 4. The following example creates a hypertext link to a URL. The user can use the set of
radio buttons to 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 [Link] property in the onMouseOver event handler.
<SCRIPT>
var destHREF="[Link]
</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='[Link] Netscape home page
<BR><INPUT TYPE="radio" NAME="destination" VALUE="sun"
onClick="destHREF='[Link] Sun home page
<BR><INPUT TYPE="radio" NAME="destination" VALUE="rfc1867"
onClick="destHREF='[Link] RFC
1867
<P><A HREF=""
onMouseOver="[Link]='Click this if you dare!'; return true"
onClick="[Link]=destHREF">
<B>Click me</B></A>
</FORM>
Example 5: links array. In the following example, the linkGetter function uses the links array to
display the value of each link in the current document. The example also defines several links and a
button for running linkGetter.
function linkGetter() {
msgWindow=[Link]("","msg","width=400,height=400")
[Link]("[Link] is " +
[Link] + "<BR>")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i] + "<BR>")
}
}
<A HREF="[Link] Home Page</A>
<A HREF="[Link] Adoptions</A>
<A HREF="[Link] Dog Chronicles</A>
<A HREF="[Link] Rescue</A>
<P>
Page No:150
<INPUT TYPE="button" VALUE="Display links"
onClick="linkGetter()">
Example 6: Refer to Area object with links array. The following code refers to the href property
of the first Area object shown in Example 1.
[Link][0].href
Example 7: Area object with onMouseOver and onMouseOut event handlers. The following
example displays an image, [Link]. 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.
<MAP NAME="worldMap">
<AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:void(0)"
onMouseOver="[Link]='You are on top of the world';return true"
onMouseOut="[Link]='You have left the top of the world';return true">
<AREA NAME="bottomWorld" COORDS="0,25,50,50" HREF="javascript:void(0)"
onMouseOver="[Link]='You are on the bottom of the world';return true"
onMouseOut="[Link]='You have left the bottom of the world';return
true">
</MAP>
<IMG SRC="images\[Link]" ALIGN="top" HEIGHT="50" WIDTH="50"
USEMAP="#worldMap">
Example 8: Simulate an Area object's onClick using the HREF attribute. The following example
uses an Area object's HREF attribute to execute a JavaScript function. The image displayed,
[Link], 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) {
[Link]=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\[Link]" ALIGN="top" HEIGHT="50" WIDTH="50"
USEMAP="#colorMap">
See also
Properties
hash
A string beginning with a hash mark (#) that specifies an anchor name in the URL.
Property of Link
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The hash property specifies a portion of the URL. This property applies to HTTP URLs only.
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 get an error.
Setting the hash property navigates to the named anchor without reloading the document. This differs
from the way a document is loaded when other link properties are set.
See also
host
A string specifying the server name, subdomain, and domain name.
Property of Link
Implemented in Navigator 2.0
Description
The host property specifies a portion of a URL. The host property is a substring of the hostname
property. The hostname property is the concatenation of the host 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 get an error.
See also
hostname
A string containing the full hostname of the server, including the server name, subdomain, domain,
and port number.
Property of Link
Description
The hostname property specifies a portion of a URL. The hostname property is the concatenation of
the host and port properties, separated by a colon. When the port property is 80 (the default), 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 get an error.
See also
Page No:152
[Link], [Link], [Link], [Link], [Link], [Link], [Link]
href
A string specifying the entire URL.
Property of Link
Description
The href property specifies the entire URL. Other link object properties are substrings of the href
property.
See also
pathname
A string specifying the URL-path portion of the URL.
Property of Link
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 get an error.
See also
port
A string specifying the communications port that the server uses.
Property of Link
Description
The port property specifies a portion of the URL. The port property is a substring of the hostname
property. The hostname property is the concatenation of the host and port properties, separated by a
colon. When the port property is 80 (the default), 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 also
Page No:153
[Link], [Link], [Link], [Link], [Link], [Link],
[Link]
protocol
A string specifying the beginning of the URL, up to and including the first colon.
Property of Link
Description
The protocol property specifies a portion of the URL. The protocol indicates the access method of
the URL. For example, the value "http:" specifies HyperText Transfer Protocol, and the value
"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 get an error.
The protocol property represents the scheme name of the URL. See Section 2.1 of RFC 1738
See also
search
A string beginning with a question mark that specifies any query information in the URL.
Property of Link
Description
The search property specifies a portion of the URL. This property applies to http URLs only.
The search property contains variable and value pairs; each pair is separated by an ampersand. For
example, two pairs in a search string could look like the following:
?x=7&y=5
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 get an error.
See also
target
A string specifying the name of the window that displays the content of a clicked hypertext link.
Property of Link
Description
The target property initially reflects the TARGET attribute of the A or AREA tags; however, setting
target overrides this attribute.
You can set target using a string, if the string represents a window name. The target property
cannot be assigned the value of a JavaScript expression or variable.
You can set the target property at any time.
Examples
Page No:154
The following example specifies that responses to the musicInfo form are displayed in the
msgWindow window:
[Link]="msgWindow"
See also
Form
text
A string containing the content of the corresponding A tag.
Property of Link
Methods
handleEvent
Invokes the handler for the specified event.
Method of Link
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
Chapter 6
Window
This chapter deals with the Window object and the client-side objects associated with it: Frame,
Location, and History.
Object Description
Frame A window that can display multiple, independently scrollable frames on a single
screen, each with its own distinct URL.
History Contains an array of information on the URLs that the client has visited within a
window.
Location Contains information on the current URL.
screen Contains properties describing the display screen and colors.
Window Represents a browser window or frame. This is the top-level object for each document,
Location, and History object group.
Frame
Page No:155
A window can display multiple, independently scrollable frames on a single screen, each with its
own distinct URL. These frames are created using the FRAME tag inside a FRAMESET tag. 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. The Frame object is a convenience for thinking about the objects that constitute
these frames. However, JavaScript actually represents a frame using a Window object. Every Frame
object is a Window object, and has all the methods and properties of a Window object. There are a
small number of minor differences between a window that is a frame and a top-level window. See
Window for complete information on frames.
Client-side object
History
Contains an array of 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 browser's Go menu.
Client-side object
Created by
History objects are predefined JavaScript objects that you access through the history property of a
Window object.
Description
To change a window's current URL without generating a history entry, you can use the
[Link] method. This replaces the current page with a new one without generating a
history entry. See [Link].
You can refer to the history entries by using the [Link] array. This array contains an entry
for each history entry in source order. Each array entry is a string containing a URL. For example, if
the history list contains three named entries, these entries are reflected as history[0], history[1],
and history[2].
If you access the history array without specifying an array element, the browser returns a string of
HTML which displays a table of URLs, each of which is a link.
Property Summary
Method Summary
Examples
Example 1. The following example goes to the URL the user visited three clicks ago in the current
window.
[Link](-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:
[Link]()
Example 3. The following example causes the second frame in a frameset to go back one item:
[Link][1].[Link]()
Page No:156
Example 4. The following example causes the frame named frame1 in a frameset to go back one
item:
[Link]()
Example 5. The following example causes the frame named frame2 in window2 to go back one item:
[Link]()
Example 6. The following code determines whether the first entry in the history array contains the
string "NETSCAPE". If it does, the function myFunction is called.
if (history[0].indexOf("NETSCAPE") != -1) {
myFunction(history[0])
}
Example 7. The following example displays the entire history list:
[Link]("<B>history is</B> " + history)
This code displays output similar to the following:
history is
Welcome to Netscape [Link]
Sun Microsystems [Link]
Royal Airways [Link]
See also
Location, [Link]
Properties
current
A string specifying the complete URL of the current history entry.
Property of History
Read-only
Examples
The following example determines whether [Link] contains the string "[Link]".
If it does, the function myFunction is called.
if ([Link]("[Link]") != -1) {
myFunction([Link])
}
See also
[Link], [Link]
length
The number of elements in the history array.
Property of History
Read-only
next
A string specifying the complete URL of the next history entry.
Property of History
Read-only
Description
The next property reflects the URL that would be used if the user chose Forward from the Go menu.
Examples
Page No:157
The following example determines whether [Link] contains the string "[Link]". If it
does, the function myFunction is called.
if ([Link]("[Link]") != -1) {
myFunction([Link])
}
See also
[Link], [Link]
previous
A string specifying the complete URL of the previous history entry.
Property of History
Read-only
Description
The previous property reflects the URL that would be used if the user chose Back from the Go
menu.
Examples
The following example determines whether [Link] contains the string "[Link]".
If it does, the function myFunction is called.
if ([Link]("[Link]") != -1) {
myFunction([Link])
}
See also
[Link], [Link]
Methods
back
Loads the previous URL in the history list.
Method of History
Syntax
back()
Parameters
None
Description
This method performs the same action as a user choosing the Back button in the browser. The back
method is the same as [Link](-1).
Examples
The following custom buttons perform the same operation as the browser's Back button:
<P><INPUT TYPE="button" VALUE="< Go Back"
onClick="[Link]()">
<P><INPUT TYPE="button" VALUE="> Go Back"
onClick="[Link]()">
Page No:158
See also
[Link], [Link]
forward
Loads the next URL in the history list.
Method of History
Syntax
forward()
Parameters
None
Description
This method performs the same action as a user choosing the Forward button in the browser. The
forward method is the same as [Link](1).
Examples
The following custom buttons perform the same operation as the browser's Forward button:
<P><INPUT TYPE="button" VALUE="< Forward"
onClick="[Link]()">
<P><INPUT TYPE="button" VALUE="> Forward"
onClick="[Link]()">
See also
[Link], [Link]
go
Loads a URL from the history list.
Method of History
Syntax
go(delta)
go(location)
Parameters
Description
The go method navigates to the location in the history list determined by the specified parameter.
If the delta argument is 0, the browser reloads the current page. If it is an integer greater than 0, 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.
The location argument is a string. Use location to load the nearest history entry whose URL
contains location as a substring. Matching the URL to the location parameter is case-insensitive.
Each section of a URL contains different information. See Location for a description of the URL
components.
Page No:159
The go method creates a new entry in the history list. To load a URL without creating an entry in the
history list, use [Link].
Examples
The following button navigates to the nearest history entry that contains the string
"[Link]":
<P><INPUT TYPE="button" VALUE="Go"
onClick="[Link]('[Link]')">
The following button navigates to the URL that is three entries backward in the history list:
<P><INPUT TYPE="button" VALUE="Go"
onClick="[Link](-3)">
Location
Contains information on the current URL.
Client-side object
Created by
Location objects are predefined JavaScript objects that you access through the location property of
a Window object:
Description
The location object represents the complete URL associated with a given Window object. Each
property of the location object represents a different portion of the URL.
protocol//host:port/pathname#hash?search
For example:
[Link]
These parts serve the following purposes:
protocol represents the beginning of the URL, up to and including the first colon.
host 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.
hash represents an anchor name fragment in the URL, including the hash mark (#). This
property applies to HTTP URLs only.
search represents any query information in the URL, including the question mark (?). This
property applies to HTTP URLs only. The search string contains variable and value pairs;
each pair is separated by an ampersand (&).
A Location object has a property for each of these parts of the URL. See the individual properties
for more information. A Location object has two other properties not shown here:
If you assign a string to the location property of an object, JavaScript creates a location object and
assigns that string to its href property. For example, the following two statements are equivalent and
set the URL of the current window to the Netscape home page:
[Link]="[Link]
[Link]="[Link]
The location object is contained by the window object and is within its scope. If you refer to a
location object without specifying a window, the location object represents the current location. If
Page No:160
you refer to a location object and specify a window name, as in [Link], the
location object represents the location of the specified window.
In event handlers, you must specify [Link] 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 [Link], which is a synonym for [Link].
Location is not a property of the document object; its equivalent is the [Link] property. The
[Link] property, which is a synonym for [Link], will be removed in a future
release.
When you set the location object or any of its properties except hash, whether a new document is
loaded depends on which version of the browser you are running:
When you specify a URL, you can use standard URL formats and JavaScript statements. Table 6.2
shows the syntax for specifying some of the most common types of URLs.
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 (by calling a void function, for example javascript:void(0)), no new page loads.
Note that loading a new page over your script's page clears the page's variables, functions, and so on.
The view-source: protocol displays HTML code that was generated with JavaScript
[Link] and [Link] methods. For information on printing and saving
generated HTML, see write.
The about: protocol provides information on Navigator and has the following syntax:
about:
about:cache
about:plugins
Page No:161
about: by itself is the same as choosing About Communicator from the Navigator Help
menu.
about:cache displays disk-cache statistics.
about:plugins displays information about plug-insyou have configured. This is the same as
choosing About Plug-ins from the Navigator Help menu.
Property Summary
Method Summary
Examples
Example 1. The following two statements are equivalent and set the URL of the current window to
the Netscape home page:
[Link]="[Link]
[Link]="[Link]
Example 2. The following statement sets the URL of a frame named frame2 to the Sun home page:
[Link]="[Link]
See also the examples for Anchor.
See also
History, [Link]
Properties
hash
A string beginning with a hash mark (#) that specifies an anchor name in the URL.
Property of Location
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The hash property specifies a portion of the URL. This property applies to HTTP URLs only.
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 get an error.
Setting the hash property navigates to the named anchor without reloading the document. This differs
from the way a document is loaded when other location properties are set.
Page No:162
Examples
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
version_2.0/script/script_info/[Link]#checkbox_object")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
The previous example displays output such as the following:
[Link] =
[Link]
version_2.0/script/script_info/[Link]#checkbox_object
[Link] = #checkbox_object
See also
host
A string specifying the server name, subdomain, and domain name.
Property of Location
Description
The host property specifies a portion of a URL. The host property is a substring of the hostname
property. The hostname property is the concatenation of the host 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 get an error.
Examples
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
version_2.0/script/script_info/[Link]#checkbox_object")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
The previous example displays output such as the following:
[Link] =
[Link]
version_2.0/script/script_info/[Link]#checkbox_object
[Link] = [Link]
See also
Page No:163
hostname
A string containing the full hostname of the server, including the server name, subdomain, domain,
and port number.
Property of Location
Description
The hostname property specifies a portion of a URL. The hostname property is the concatenation of
the host and port properties, separated by a colon. When the port property is 80 (the default), 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 get an error.
Examples
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
version_2.0/script/script_info/[Link]#checkbox_object")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
The previous example displays output such as the following:
[Link] =
[Link]
version_2.0/script/script_info/[Link]#checkbox_object
[Link] = [Link]
See also
href
A string specifying the entire URL.
Property of Location
Description
The href property specifies the entire URL. Other location object properties are substrings of the
href property. If you want to change the URL associated with a window, you should do so by
changing the href property; this correctly updates all of the other properties.
Omitting a property name from the location object is equivalent to specifying [Link]. For
example, the following two statements are equivalent and set the URL of the current window to the
Netscape home page:
[Link]="[Link]
[Link]="[Link]
Examples
Page No:164
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display all the properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
version_2.0/script/script_info/[Link]#checkbox_object")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
The previous example displays output such as the following:
[Link] =
[Link]
version_2.0/script/script_info/[Link]#checkbox_object
[Link] = http:
[Link] = [Link]
[Link] = [Link]
[Link] =
[Link] =
/comprod/products/navigator/version_2.0/script/
script_info/[Link]
[Link] = #checkbox_object
[Link] =
See also
pathname
A string specifying the URL-path portion of the URL.
Property of 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 get an error.
Examples
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
version_2.0/script/script_info/[Link]#checkbox_object")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
Page No:165
[Link] + "<P>")
[Link]()
The previous example displays output such as the following:
[Link] =
[Link]
version_2.0/script/script_info/[Link]#checkbox_object
[Link] =
/comprod/products/navigator/version_2.0/script/
script_info/[Link]
See also
port
A string specifying the communications port that the server uses.
Property of Location
Description
The port property specifies a portion of the URL. The port property is a substring of the hostname
property. The hostname property is the concatenation of the host and port properties, separated by a
colon.
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 get an error. If the
port property is not specified, it defaults to 80.
Examples
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
version_2.0/script/script_info/[Link]#checkbox_object")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
The previous example displays output such as the following:
[Link] =
[Link]
version_2.0/script/script_info/[Link]#checkbox_object
[Link] =
See also
protocol
A string specifying the beginning of the URL, up to and including the first colon.
Property of Location
Description
Page No:166
The protocol property specifies a portion of the URL. The protocol indicates the access method of
the URL. For example, the value "http:" specifies HyperText Transfer Protocol, and the value
"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 get an error.
Examples
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
version_2.0/script/script_info/[Link]#checkbox_object")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
The previous example displays output such as the following:
[Link] =
[Link]
version_2.0/script/script_info/[Link]#checkbox_object
[Link] = http:
See also
search
A string beginning with a question mark that specifies any query information in the URL.
Property of Location
Description
The search property specifies a portion of the URL. This property applies to HTTP URLs only.
The search property contains variable and value pairs; each pair is separated by an ampersand. For
example, two pairs in a search string could look as follows:
?x=7&y=5
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 get an error.
Examples
In the following example, the [Link] statement creates a window called newWindow and loads
the specified URL into it. The [Link] statements display properties of
[Link] in a window called msgWindow.
newWindow=[Link]
("[Link]
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
[Link]("[Link] = " +
[Link] + "<P>")
[Link]()
The previous example displays the following output:
Page No:167
[Link] =
[Link]
[Link] = ?qt=RFC+1738+&col=WW
See also
Methods
reload
Forces a reload of the window's current document (the document specified by the [Link]
property).
Method of Location
Syntax
reload(forceGet)
Parameters
forceGet (Optional) If you supply 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 (for
example, if it is generated by a CGI on each request).
Description
This method uses the same policy that the browser's Reload button uses. The user interface for setting
the default value of this policy varies for different browser versions.
By default, the reload method does not force a transaction with the server. However, if the user has
set the preference to check every time, the method 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 reloads from the cache,
unless the user has specified to check every time and the document has changed on the server since it
was last loaded and saved in the cache.
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) {
[Link][0].src=theImage
}
</SCRIPT>
<FORM NAME="imageForm">
<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="displayImage('[Link]')">Sea otter
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="displayImage('[Link]')">Killer whale
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="displayImage('[Link]')">Humpback whale
<BR>
<IMG NAME="marineMammal" SRC="[Link]" ALIGN="left" VSPACE="10">
<P><INPUT TYPE="button" VALUE="Click here to reload"
onClick="[Link]()">
</FORM>
Page No:168
See also
[Link]
replace
Loads the specified URL over the current history entry.
Method of Location
Implemented in Navigator 3.0
Syntax
replace("URL")
Parameters
Description
The replace method loads the specified URL over the current history entry. After calling the
replace method, the user cannot navigate to the previous URL by using browser's Back button.
If your program will be run with JavaScript in Navigator 2.0, you could put the following line in a
SCRIPT tag early in your program. This emulates replace, which was introduced in Navigator 3.0:
if ([Link] == null)
[Link] = [Link]
The replace method does not create a new entry in the history list. To create an entry in the history
list while loading a URL, use the [Link] method.
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. After invoking displayCatalog,
the user cannot navigate to the previous URL (the list of catalogs) by using browser's Back button.
<SCRIPT>
function displayCatalog() {
var seaName=""
var catName=""
for (var i=0; i < [Link]; i++) {
if ([Link][i].checked) {
seaName=[Link][i].value
i=[Link]
}
}
for (var i in [Link]) {
if ([Link][i].checked) {
catName=[Link][i].value
i=[Link]
}
}
fileName=seaName + catName + ".html"
[Link](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
Page No:169
<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>
screen
Contains properties describing the display screen and colors.
Client-side object
Created by
The JavaScript runtime engine creates the screen object for you. You can access its properties
automatically.
Description
This object contains read-only properties that allow you to get information about the user's display.
Property Summary
availHeightSpecifies the height of the screen, in pixels, minus permanent or semipermanent user
interface features displayed by the operating system, such as the Taskbar on Windows.
availWidth Specifies the width of the screen, in pixels, minus permanent or semipermanent user
interface features displayed by the operating system, such as the Taskbar on Windows.
colorDepth The bit depth of the color palette, if one is in use; otherwise, the value is derived from
[Link].
height Display screen height.
pixelDepth Display screen color resolution (bits per pixel).
width Display screen width.
Examples
The following function creates a string containing the current display properties:
function screen_properties() {
[Link] = "("+[Link]+" x
"+[Link]+") pixels, "+
[Link] +" bit depth, "+
[Link] +" bit color palette depth.";
} // end function screen_properties
Properties
availHeight
Specifies the height of the screen, in pixels, minus permanent or semipermanent user interface
features displayed by the operating system, such as the Taskbar on Windows.
Property of screen
availWidth
Specifies the width of the screen, in pixels, minus permanent or semipermanent user interface
features displayed by the operating system, such as the Taskbar on Windows.
Property of screen
Page No:170
colorDepth
The bit depth of the color palette in bits per pixel, if a color palette is in use. Otherwise, this property
is derived from [Link].
Property of screen
height
Display screen height, in pixels.
Property of screen
pixelDepth
Display screen color resolution, in bits per pixel.
Property of screen
width
Display screen width, in pixels.
Property of screen
Window
Represents a browser window or frame. This is the top-level object for each document, Location,
and History object group.
Client-side object.
Created by
The JavaScript runtime engine creates a Window object for each BODY or FRAMESET tag. It also creates
a Window object to represent each frame defined in a FRAME tag. In addition, you can create other
windows by calling the [Link] method. For details on defining a window, see open.
Event handlers
onBlur
onDragDrop
onError
onFocus
onLoad
onMove
onResize
onUnload
In Navigator 3.0, on some platforms, placing an onBlur or onFocus event handler in a FRAMESET tag
has no effect.
Description
The Window object is the top-level object in the JavaScript client hierarchy. A Window object can
represent either a top-level window or a frame inside a frameset. As a matter of convenience, you can
think about a Frame object as a Window object that isn't a top-level window. However, there is not
really a separate Frame class; these objects really are Window objects, with a very few minor
differences:
Page No:171
For a top-level window, the parent and top properties are references to the window itself.
For a frame, the top refers to the topmost browser window, and parent refers to the parent
window of the current window.
For a top-level window, setting the defaultStatus or status property sets the text
appearing in the browser status line. For a frame, setting these properties only sets the status
line text when the cursor is over the frame.
The close method is not useful for windows that are frames.
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).
If a FRAME tag contains SRC and NAME attributes, you can refer to that frame from a sibling
frame by using [Link] or [Link][index]. For example, if the fourth
frame in a set has NAME="homeFrame", sibling frames can refer to that frame using
[Link] or [Link][3].
For all windows, the self and window properties of a Window object 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 the close method of either window or self. You can use these
properties to make your code more readable or to disambiguate the property reference [Link]
from a form called status. See the properties and methods listed below for more examples.
Because the existence of the current window is assumed, you do not have to refer to 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
[Link]() or [Link]() 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
[Link]().
For the same reason, when you refer to the location object within an event handler, you must
specify [Link] instead of simply using location. A call to location without specifying
an object name is equivalent to [Link], which is a synonym for [Link].
You can refer to a window's Frame objects in your code by using the frames array. In a window with
a FRAMESET tag, the frames array contains an entry for each frame.
A windows lacks event handlers until HTML that contains a BODY or FRAMESET tag is loaded into it.
Property Summary
Page No:172
pageXOffset Provides the current x-position, in pixels, of a window's viewed page.
pageYOffset Provides the current y-position, in pixels, of a window's viewed page.
parent A synonym for a window or frame whose frameset contains the current frame.
personalbar Represents the browser window's personal bar (also called the directories bar).
scrollbars Represents the browser window's scroll bars.
self A synonym for the current window.
status Specifies a priority or transient message in the window's status bar.
statusbar Represents the browser window's status bar.
toolbar Represents the browser window's tool bar.
top A synonym for the topmost browser window.
window A synonym for the current window.
Method Summary
Page No:173
Examples
Example 1. Windows opening other windows. In the following example, the document in the top
window opens a second window, window2, and defines push buttons 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.
[Link], 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("[Link]","secondWindow",
"scrollbars=yes,width=250, height=400")
[Link]("<B>The first window has no name: "
+ [Link] + "</B>")
[Link]("<BR><B>The second window is named: "
+ [Link] + "</B>")
</SCRIPT>
<FORM NAME="form1">
<P><INPUT TYPE="button" VALUE="Open a message window"
onClick = "window3=[Link]('','messageWindow',
'scrollbars=yes,width=175, height=300')">
<P><INPUT TYPE="button" VALUE="Write to the message window"
onClick="[Link]('Hey there');
[Link]()">
<P><INPUT TYPE="button" VALUE="Close the message window"
onClick="[Link]()">
<P><INPUT TYPE="button" VALUE="Close window2"
onClick="[Link]()">
</FORM>
</BODY>
</HTML>
[Link], 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 ' + [Link] + ': Hello, World.')"
onUnload="alert('Message from ' + [Link] + ': I\'m closing')">
<B>Some numbers</B>
<UL><LI>one
<LI>two
<LI>three
<LI>four</UL>
</BODY>
</HTML>
Example 2. Creating frames. The following example creates two windows, each with four frames.
In the first window, the first frame contains push buttons that change the background colors of the
frames in both windows. [Link], which defines the frames for the first window, contains the
following code:
<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 1</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%"
onLoad="alert('Hello, World.')">
<FRAME SRC=[Link] NAME="frame1">
<FRAME SRC=[Link] NAME="frame2">
<FRAME SRC=[Link] NAME="frame3">
<FRAME SRC=[Link] NAME="frame4">
</FRAMESET>
</HTML>
[Link], which defines the frames for the second window, contains the following code:
Page No:174
<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 2</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%">
<FRAME SRC=[Link] NAME="frame1">
<FRAME SRC=[Link] NAME="frame2">
<FRAME SRC=[Link] NAME="frame3">
<FRAME SRC=[Link] NAME="frame4">
</FRAMESET>
</HTML>
[Link], 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="[Link]" target=frame2>Click here</A>
to load a different file into frame 2.
<SCRIPT>
window2=open("[Link]","secondFrameset")
</SCRIPT>
<FORM>
<P><INPUT TYPE="button" VALUE="Change frame2 to teal"
onClick="[Link]='teal'">
<P><INPUT TYPE="button" VALUE="Change frame3 to slateblue"
onClick="[Link][2].[Link]='slateblue'">
<P><INPUT TYPE="button" VALUE="Change frame4 to darkturquoise"
onClick="[Link][3].[Link]='darkturquoise'">
<P><INPUT TYPE="button" VALUE="window2.frame2 to violet"
onClick="[Link]='violet'">
<P><INPUT TYPE="button" VALUE="window2.frame3 to fuchsia"
onClick="[Link][2].[Link]='fuchsia'">
<P><INPUT TYPE="button" VALUE="window2.frame4 to deeppink"
onClick="[Link][3].[Link]='deeppink'">
</FORM>
</BODY>
</HTML>
[Link], which defines the content for the remaining frames, contains the following code:
<HTML>
<BODY>
<P>This is a frame.
</BODY>
</HTML>
[Link], which is referenced in a Link object in [Link], contains the following
code:
<HTML>
<BODY>
<P>This is a frame. What do you think?
</BODY>
</HTML>
See also
document, Frame
Properties
closed
Specifies whether a window is closed.
Property of Window
Read-only
Description
Page No:175
The closed property is a boolean value that specifies whether a window has been closed. When a
window closes, the window object that represents it continues to exist, and its closed property is set
to true.
Use closed to determine whether a window that you opened, and to which you still hold a reference
(from the return value of [Link]), is still open. Once a window is closed, you should not
attempt to manipulate it.
Examples
Example 1. The following code opens a window, win1, then later checks to see if that window has
been closed. A function is called depending on whether win1 is closed.
win1=[Link]('[Link]','window1','width=300,height=300')
...
if ([Link])
function1()
else
function2()
Example 2. The following code determines if the current window's opener window is still closed,
and calls the appropriate function.
if ([Link])
function1()
else
function2()
See also
[Link], [Link]
defaultStatus
The default message displayed in the status bar at the bottom of the window.
Property of Window
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
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 onMouseOut or onMouseOver event handlers.
Examples
In the following example, the statusSetter function sets both the status and defaultStatus
properties in an onMouseOver event handler:
function statusSetter() {
[Link] = "Click the link for the Netscape home page"
[Link] = "Netscape home page"
}
<A HREF="[Link]
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.
Page No:176
See also
[Link]
document
Contains information on the current document, and provides methods for displaying HTML output to
the user.
Property of Window
Description
frames
An array of objects corresponding to child frames (created with the FRAME tag) in source order.
Property of Window
Read-only
You can refer to the child frames of a window by using the frames array. This array contains an
entry for each child frame (created with the FRAME tag) in a window containing a FRAMESET tag; the
entries are in source order. For example, if a window contains three child frames whose NAME
attributes are fr1, fr2, and fr3, you can refer to the objects in the images array either as:
[Link]["fr1"]
[Link]["fr2"]
[Link]["fr3"]
or as:
[Link][0]
[Link][1]
[Link][2]
You can find out how many child frames the window has by using the length property of the Window
itself or of the frames array.
The value of each element in the frames array is <object nameAttribute>, where nameAttribute
is the NAME attribute of the frame.
history
Contains information on the URLs that the client has visited within a window.
Property of Window
Description
innerHeight
Specifies the vertical dimension, in pixels, of the window's content area.
Property of Window
Description
To create a window smaller than 100 x 100 pixels, set this property in a signed script.
See also
Page No:177
[Link], [Link], [Link]
innerWidth
Specifies the horizontal dimension, in pixels, of the window's content area.
Property of Window
Description
To create a window smaller than 100 x 100 pixels, set this property in a signed script.
See also
length
The number of child frames in the window.
Property of Window
Read-only
Description
This property gives you the same result as using the length property of the frames array.
location
Contains information on the current URL.
Property of Window
Description
locationbar
Represents the browser window's location bar (the region containing the bookmark and URL areas).
Property of Window
Description
The value of the locationbar property itself has one property, visible. If true, the location bar is
visible; if false, it is hidden.
Security
Setting the value of the location bar's visible property requires the UniversalBrowserWrite
privilege.
Examples
The following example would make the referenced window "chromeless" (chromeless windows lack
toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user
interface toolbars:
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
Page No:178
[Link]=false;
[Link]=false;
menubar
Represents the browser window's menu bar. This region contains browser's drop-down menus such as
File, Edit, View, Go, Communicator, and so on.
Property of Window
Description
The value of the menubar property itself one property, visible. If true, the menu bar is visible; if
false, it is hidden.
Security
Setting the value of the menu bar's visible property requires the UniversalBrowserWrite
privilege..
Examples
The following example would make the referenced window "chromeless" (chromeless windows lack
toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user
interface toolbars:
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
name
A string specifying the window's name.
Property of Window
Read-only (2.0); Modifiable (later versions)
Description
In Navigator 2.0, NAME was a read-only property. In later versions, this property is modifiable by your
code. This allows you to assign a name to a top-level window.
Examples
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=[Link]("[Link]
alert([Link])
opener
Specifies the window of the calling document when a window is opened using the open method.
Property of Window
Page No:179
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.
You may use [Link] to open a new window and then use [Link] on that window to
open another window, and so on. In this way, you can end up with a chain of opened windows, each
of which has an opener property pointing to the window that opened it.
Communicator allows a maximum of 100 windows to be around at once. If you open window2 from
window1 and then are done with window1, be sure to set the opener property of window2 to null.
This allows JavaScript to garbage collect window1. If you do not set the opener property to null, the
window1 object remains, even though it's no longer really needed.
Examples
Example 1: Close the opener. The following code closes the window that opened the current
window. When the opener window closes, opener is unchanged. However, [Link]
then evaluates to undefined.
[Link]()
Example 2: Close the main browser window.
[Link]()
Example 3: Evaluate the name of the opener. A window can determine the name of its opener as
follows:
[Link]("<BR>opener property is " + [Link])
Example 4: 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.
[Link]=null
Example 5: Change a property of the opener. The following code changes the background color of
the window specified by the opener property.
[Link]='bisque'
See also
[Link], [Link]
outerHeight
Specifies the vertical dimension, in pixels, of the window's outside boundary.
Property of Window
Description
The outer boundary includes the scroll bars, the status bar, the tool bars, and other "chrome" (window
border user interface elements). To create a window smaller than 100 x 100 pixels, set this property
in a signed script.
See also
outerWidth
Page No:180
Specifies the horizontal dimension, in pixels, of the window's outside boundary.
Property of Window
Description
The outer boundary includes the scroll bars, the status bar, the tool bars, and other "chrome" (window
border user interface elements). To create a window smaller than 100 x 100 pixels, set this property
in a signed script.
See also
pageXOffset
Provides the current x-position, in pixels, of a window's viewed page.
Property of Window
Read-only
Description
The pageXOffset property provides the current x-position of a page as it relates to the upper-left
corner of the window's content area. This property is useful when you need to find the current
location of the scrolled page before using scrollTo or scrollBy.
Example
See Also
[Link]
pageYOffset
Provides the current y-position, in pixels, of a window's viewed page.
Property of Window
Read-only
Description
The pageYOffset property provides the current y-position of a page as it relates to the upper-left
corner of the window's content area. This property is useful when you need to find the current
location of the scrolled page before using scrollTo or scrollBy.
Example
See also
[Link]
parent
The parent property is the window or frame whose frameset contains the current frame.
Page No:181
Property of Window
Read-only
Description
This property is only meaningful for frames; that is, windows that are not top-level windows.
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 in one of the following ways:
[Link]
[Link][index]
For example, if the fourth frame in a set has NAME="homeFrame", sibling frames can refer to that
frame using [Link] or [Link][3].
You can use [Link] to refer to the "grandparent" frame or window when a FRAMESET tag is
nested within a child frame.
<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
personalbar
Represents the browser window's personal bar (also called the directories bar). This is the region the
user can use for easy access to certain bookmarks.
Property of Window
Description
The value of the personalbar property itself one property, visible. If true, the personal bar is
visible; if false, it is hidden.
Security
Setting the value of the personal bar's visible property requires the UniversalBrowserWrite
privilege. For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the
JavaScript Guide.
Examples
The following example would make the referenced window "chromeless" (chromeless windows lack
toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user
interface toolbars:
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
scrollbars
Represents the browser window's vertical and horizontal scroll bars for the document area.
Page No:182
Property of Window
Description
The value of the scrollbars property itself has one property, visible. If true, both scrollbars are
visible; if false, they are hidden.
Security
Setting the value of the scrollbars' visible property requires the UniversalBrowserWrite privilege.
For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Examples
The following example would make the referenced window "chromeless" (chromeless windows lack
toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user
interface toolbars:
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
self
The self property is a synonym for the current window.
Property of Window
Read-only
Description
The self property refers to the current window. That is, the value of this property is a synonym for
the object itself.
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.
<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
In the following example, [Link] 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="[Link]=pickRandomURL()"
onMouseOver="[Link]='Pick a random URL' ; return true">
Go!</A>
status
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.
Property of Window
Page No:183
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
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="[Link]=pickRandomURL()"
onMouseOver="[Link]='Pick a random URL'; return true">
Go!</A>
In the preceding example, the status property of the window is assigned to the window's self
property, as [Link].
See also
[Link]
statusbar
Represents the browser window's status bar. This is the region containing the security indicator,
browser status, and so on.
Property of Window
Description
The value of the statusbar property itself one property, visible. If true, the status bar is visible; if
false, it is hidden.
Security
Setting the value of the status bar's visible property requires the UniversalBrowserWrite
privilege. For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the
JavaScript Guide.
Examples
The following example would make the referenced window "chromeless" (chromeless windows lack
toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user
interface toolbars:
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
toolbar
Page No:184
Represents the browser window's tool bar, containing the navigation buttons, such as Back, Forward,
Reload, Home, and so on.
Property of Window
Description
The value of the toolbar property itself one property, visible. If true, the tool bar is visible; if
false, it is hidden.
Security
Setting the value of the tool bar's visible property requires the UniversalBrowserWrite privilege.
For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Examples
The following example would make the referenced window "chromeless" (chromeless windows lack
toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user
interface toolbars:
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
[Link]=false;
top
The top property is a synonym for the topmost browser window, which is a document window or
web browser window.
Property of Window
Read-only
Description
The top property refers to the topmost window that contains frames or nested framesets. Use the top
property to refer to this ancestor window.
<object objectReference>
where objectReference is an internal reference.
Examples
The statement [Link] specifies the number of frames contained within the topmost ancestor
window. When the topmost ancestor is defined as follows, [Link] returns three:
<FRAMESET COLS="30%,40%,30%">
<FRAME SRC=[Link] NAME="childFrame1">
<FRAME SRC=[Link] NAME="childFrame2">
<FRAME SRC=[Link] NAME="childFrame3">
</FRAMESET>
The following example sets the background color of a frame called myFrame to red. myFrame is a
child of the topmost ancestor window.
[Link]="red"
Page No:185
window
The window property is a synonym for the current window or frame.
Property of Window
Read-only
Description
The window property refers to the current window or frame. That is, the value of this property is a
synonym for the object itself.
Although you can use the window property as a synonym for the current frame, your code may be
more readable if you use the self property. For example, [Link] and [Link] both specify
the name of the current frame, but [Link] may be easier to understand (because a frame is not
displayed as a separate window).
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.
<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, [Link] 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="[Link]=pickRandomURL()"
onMouseOver="[Link]='Pick a random URL' ; return true">
Go!</A>
See also
[Link]
Methods
alert
Displays an Alert dialog box with a message and an OK button.
Method of Window
Syntax
alert("message")
Parameters
message A string.
Description
Page No:186
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.
You cannot specify a title for an alert dialog box, but you can use the open method to create your
own alert dialog box. See open.
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 ([Link] > 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([Link])">
See also
[Link], [Link]
back
Undoes the last history step in any frame within the top-level window; equivalent to the user pressing
the browser's Back button.
Method of Window
Syntax
back()
Parameters
None
Description
Calling the back method is equivalent to the user pressing the browser's Back button. That is, back
undoes the last step anywhere within the top-level window, whether it occurred in the same frame or
in another frame in the tree of frames loaded from the top-level window. In contrast, the history
object's back method backs up the current window or frame history one step.
For example, consider the following scenario. While in Frame A, you click the Forward button to
change Frame A's content. You then move to Frame B and click the Forward button to change Frame
B's content. If you move back to Frame A and call [Link](), the content of Frame B changes
(clicking the Back button behaves the same).
The following custom buttons perform the same operation as the browser's Back button:
<P><INPUT TYPE="button" VALUE="< Go Back"
onClick="[Link]()">
<P><INPUT TYPE="button" VALUE="> Go Back"
onClick="[Link]()">
See also
[Link], [Link]
blur
Removes focus from the specified object.
Method of Window
Syntax
blur()
Parameters
None
Description
Use the blur method to remove focus from a specific window or frame. Removing focus from a
window sends the window to the background in most windowing systems.
See also
[Link]
captureEvents
Sets the window to capture all events of the specified type.
Method of Window
Syntax
captureEvents(eventType)
Parameters
eventType The type of event to be captured. The available event types are listed with the event
object.
Security
When a window with frames wants to capture events in pages loaded from different locations
(servers), you need to use captureEvents in a signed script and precede it with
enableExternalCapture. You must have the UniversalBrowserWrite privilege. For more
information and an example, see enableExternalCapture. For information on security in
Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript Guide.
See also
Page No:188
captureEvents works in tandem with releaseEvents, routeEvent, and handleEvent. For more
information, see "Events in Navigator 4.0".
clearInterval
Cancels a timeout that was set with the setInterval method.
Method of Window
Syntax
clearInterval(intervalID)
Parameters
intervalID Timeout setting that was returned by a previous call to the setInterval method.
Description
See setInterval.
Examples
See setInterval.
See also
[Link]
clearTimeout
Cancels a timeout that was set with the setTimeout method.
Method of Window
Syntax
clearTimeout(timeoutID)
Parameters
timeoutID A timeout setting that was returned by a previous call to the setTimeout method.
Description
See setTimeout.
Examples
See setTimeout.
See also
[Link], [Link]
close
Closes the specified window.
Method of Window
Page No:189
Syntax
close()
Parameters
None
Security
Navigator 4.0: To unconditionally close a window, you need the UniversalBrowserWrite privilege.
For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Description
The close method closes the specified window. If you call close without specifying a
windowReference, JavaScript closes the current window.
The close method 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 [Link](). 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.
In event handlers, you must specify [Link]() 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 [Link]().
Examples
See also
[Link], [Link]
confirm
Displays a Confirm dialog box with the specified message and OK and Cancel buttons.
Method of Window
Syntax
confirm("message")
Parameters
message A string.
Page No:190
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.
You cannot specify a title for a confirm dialog box, but you can use the open method to create your
own confirm dialog. See open.
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 push button, as
shown in the following example:
<INPUT TYPE="button" VALUE="Quit" onClick="confirmCleanUp()">
See also
[Link], [Link]
disableExternalCapture
Disables external event capturing set by the enableExternalCapture method.
Method of Window
Syntax
disableExternalCapture()
Parameters
None
Description
See enableExternalCapture.
enableExternalCapture
Allows a window with frames to capture events in pages loaded from different locations (servers).
Method of Window
Page No:191
Syntax
enableExternalCapture()
Parameters
None
Description
Use this method in a signed script requesting UniversalBrowserWrite privileges, and use it before
calling the captureEvents method.
If Communicator sees additional scripts that cause the set of principals in effect for the container to
be downgraded, it disables external capture of events. Additional calls to enableExternalCapture
(after acquiring the UniversalBrowserWrite privilege under the reduced set of principals) can be
made to enable external capture again.
Example
In the following example, the window is able to capture all Click events that occur across its frames.
<SCRIPT ARCHIVE="[Link]" ID="2">
function captureClicks() {
[Link](
"UniversalBrowserWrite");
enableExternalCapture();
captureEvents([Link]);
...
}
</SCRIPT>
See also
[Link], [Link]
find
Finds the specified text string in the contents of the specified window.
Method of Window
Syntax
Parameters
Returns
Description
When a string is specified, the browser performs a case-insensitive, forward search. If a string is not
specified, the method displays the Find dialog box, allowing the user to enter a search string.
Page No:192
focus
Gives focus to the specified object.
Method of Window
Syntax
focus()
Parameters
None
Description
Use the focus method to navigate to a specific window or frame, and give it focus. Giving focus to a
window brings the window forward in most windowing systems.
In Navigator 3.0, on some platforms, the focus method gives focus to a frame but the focus is not
visually apparent (for example, the frame's border is not darkened).
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 reenter the password.
function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
[Link]()
[Link]()
}
}
This example assumes that the Password object is defined as
<INPUT TYPE="password" NAME="userPass">
See also
[Link]
forward
Points the browser to the next URL in the current history list; equivalent to the user pressing the
browser's Forward button
Method of Window
Syntax
[Link]()
forward()
Parameters
None
Description
This method performs the same action as a user choosing the Forward button in the browser. The
forward method is the same as [Link](1).
Page No:193
When used with the Frame object, forward behaves as follows: While in Frame A, you click the
Back button to change Frame A's content. You then move to Frame B and click the Back button to
change Frame B's content. If you move back to Frame A and call [Link](), the content of
Frame B changes (clicking the Forward button behaves the same). If you want to navigate Frame A
separately, use [Link]().
Examples
The following custom buttons perform the same operation as the browser's Forward button:
<P><INPUT TYPE="button" VALUE="< Go Forth"
onClick="[Link]()">
<P><INPUT TYPE="button" VALUE="> Go Forth"
onClick="[Link]()">
See also
[Link]
handleEvent
Invokes the handler for the specified event.
Method of Window
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
Description
handleEvent works in tandem with captureEvents, releaseEvents, and routeEvent. For more
information, see "Events in Navigator 4.0".
home
Points the browser to the URL specified in preferences as the user's home page; equivalent to the user
pressing the browser's Home button.
Method of Window
Syntax
home()
Parameters
None
Description
This method performs the same action as a user choosing the Home button in the browser.
moveBy
Moves the window relative to its current position, moving the specified number of pixels.
Method of Window
Page No:194
Syntax
moveBy(horizontal, vertical)
Parameters
Description
This method moves the window by adding or subtracting the specified number of pixels to the current
location.
Security
Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed
JavaScript, so a window won't move past the screen boundaries. You need the
UniversalBrowserWrite privilege for this. For information on security in Navigator 4.0, see
Chapter 7, "JavaScript Security," in the JavaScript Guide.
Examples:
To move the current window 5 pixels up towards the top of the screen (x-axis), and 10 pixels towards
the right (y-axis) of the current window position, use this statement:
[Link](-5,10); // relative positioning
See also
[Link]
moveTo
Moves the top-left corner of the window to the specified screen coordinates.
Method of Window
Syntax
moveTo(x-coordinate, y-coordinate)
Parameters
Description
This method moves the window to the absolute pixel location indicated by its parameters. The origin
of the axes is at absolute position (0,0); this is the upper left-hand corner of the display.
Security
Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed
JavaScript, so a window won't move past the screen boundaries. You need the
UniversalBrowserWrite privilege for this. For information on security in Navigator 4.0, see
Chapter 7, "JavaScript Security," in the JavaScript Guide.
Examples:
Page No:195
To move the current window to 25 pixels from the top boundary of the screen (x-axis), and 10 pixels
from the left boundary of the screen (y-axis), use this statement:
[Link](25,10); // absolute positioning
See also
[Link]
open
Opens a new web browser window.
Method of Window
Syntax
Parameters
URL A string specifying the URL to open in the new window. See the Location object
for a description of the URL components.
windowName A string specifying the window name to use in the TARGET attribute of a FORM or A
tag. windowName can contain only alphanumeric or underscore (_) characters.
windowFeatures (Optional) A string containing a comma-separated list determining whether or not
to create various standard window features. These options are described below.
Description
In event handlers, you must specify [Link]() 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 [Link]().
The open method opens a new Web browser window on the client, similar to choosing New
Navigator Window from the File menu of the browser. The URL argument specifies the URL
contained by the new window. If URL is an empty string, a new, empty window is created.
You can use open on an existing window, and if you pass the empty string for the URL, you will get
a reference to the existing window, but not load anything into it. You can, for example, then look for
properties in the window.
windowFeatures is an optional string containing a comma-separated list of options for the new
window (do not include any spaces in this list). After a window is open, you cannot use JavaScript to
change the windowFeatures. The features you can specify are:
alwaysLowered(Navigator 4.0) If yes, creates a new window that floats below other windows,
whether it is active or not. This is a secure feature and must be set in signed scripts.
alwaysRaised (Navigator 4.0) If yes, creates a new window that floats on top of other windows,
whether it is active or not. This is a secure feature and must be set in signed scripts.
dependent (Navigator 4.0) If yes, creates a new window as a child of the current window. A
dependent window closes when its parent window closes. On Windows platforms, a
dependent window does not show on the task bar.
directories If yes, creates the standard browser directory buttons, such as What's New and
What's Cool.
height (Navigator 2.0 and 3.0) Specifies the height of the window in pixels.
hotkeys (Navigator 4.0) If no (or 0), disables most hotkeys in a new window that has no
menu bar. The security and quit hotkeys remain enabled.
innerHeight (Navigator 4.0) Specifies the height, in pixels, of the window's content area. To
create a window smaller than 100 x 100 pixels, set this feature in a signed script.
Page No:196
This feature replaces height, which remains for backwards compatibility.
innerWidth (Navigator 4.0) Specifies the width, in pixels, of the window's content area. To
create a window smaller than 100 x 100 pixels, set this feature in a signed script.
This feature replaces width, which remains for backwards compatibility.
location If yes, creates a Location entry field.
menubar If yes, creates the menu at the top of the window.
outerHeight (Navigator 4.0) Specifies the vertical dimension, in pixels, of the outside boundary
of the window. To create a window smaller than 100 x 100 pixels, set this feature in
a signed script.
resizable If yes, allows a user to resize the window.
screenX (Navigator 4.0) Specifies the distance the new window is placed from the left side
of the screen. To place a window offscreen, set this feature in a signed scripts.
screenY (Navigator 4.0) Specifies the distance the new window is placed from the top of the
screen. To place a window offscreen, set this feature in a signed scripts.
scrollbars If yes, creates horizontal and vertical scrollbars when the Document grows larger
than the window dimensions.
status If yes, creates the status bar at the bottom of the window.
titlebar (Navigator 4.0) If yes, creates a window with a title bar. To set the titlebar to no, set
this feature in a signed script.
toolbar If yes, creates the standard browser toolbar, with buttons such as Back and Forward.
width (Navigator 2.0 and 3.0) Specifies the width of the window in pixels.
z-lock (Navigator 4.0) If yes, creates a new window that does not rise above other
windows when activated. This is a secure feature and must be set in signed scripts.
Many of these features (as noted above) can either be yes or no. For these features, you can use 1
instead of yes and 0 instead of no. If you want to turn a feature on, you can also simply list the feature
name in the windowFeatures string.
If windowName does not specify an existing window and you do not supply the windowFeatures
parameter, all of the features which have a yes/no choice are yes by default. However, if you do
supply the windowFeatures parameter, then the titlebar and hotkeys are still yes by default, but
the other features which have a yes/no choice are no by default.
For example, all of the following statements turn on the toolbar option and turn off all other Boolean
options:
You may use open to open a new window and then use open on that window to open another
window, and so on. In this way, you can end up with a chain of opened windows, each of which has
an opener property pointing to the window that opened it.
Communicator allows a maximum of 100 windows to be around at once. If you open window2 from
window1 and then are done with window1, be sure to set the opener property of window2 to null.
This allows JavaScript to garbage collect window1. If you do not set the opener property to null, the
window1 object remains, even though it's no longer really needed.
Security
Page No:197
To perform the following operations using the specified screen features, you need the
UniversalBrowserWrite privilege:
To create a window smaller than 100 x 100 pixels or larger than the screen can accommodate
by using innerWidth, innerHeight, outerWidth, and outerHeight.
To place a window off screen by using screenX and screenY.
To create a window without a titlebar by using titlebar.
To use alwaysRaised, alwaysLowered, or z-lock for any setting.
For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Examples
Example 1. In the following example, the windowOpener function opens a window and uses write
methods to display a message:
function windowOpener() {
msgWindow=[Link]("","displayWindow","menubar=yes")
[Link]
("<HEAD><TITLE>Message window</TITLE></HEAD>")
[Link]
("<CENTER><BIG><B>Hello, world!</B></BIG></CENTER>")
}
Example 2. The following is an onClick event handler that opens a new client window displaying
the content specified in the file [Link]. 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="[Link] ('[Link]', 'newWin',
'scrollbars=yes,status=yes,width=300,height=300')">
</FORM>
See also
[Link]
print
Prints the contents of the window.
Method of Window
Syntax
print()
Parameters
None
prompt
Displays a Prompt dialog box with a message and an input field.
Method of Window
Syntax
prompt(message, inputDefault)
Parameters
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 <undefined>.
You cannot specify a title for a prompt dialog box, but you can use the open method to create your
own prompt dialog. See open.
Examples
See also
[Link], [Link]
releaseEvents
Sets the window or document to release captured events of the specified type, sending the event to
objects further along the event hierarchy.
Method of Window
Note
If the original target of the event is a window, the window receives the event even if it is set to
release that type of event.
Syntax
releaseEvents(eventType)
Parameters
Description
releaseEvents works in tandem with captureEvents, routeEvent, and handleEvent. For more
information, see "Events in Navigator 4.0".
resizeBy
Resizes an entire window by moving the window's bottom-right corner by the specified amount.
Method of Window
Syntax
Page No:199
resizeBy(horizontal, vertical)
Parameters
Description
This method changes the window's dimensions by setting its outerWidth and outerHeight
properties. The upper left-hand corner remains anchored and the lower right-hand corner moves.
resizeBy moves the window by adding or subtracting the specified number of pixels to that corner's
current location.
Security
Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed
JavaScript, so a window won't move past the screen boundaries. In addition, windows have an
enforced minimum size of 100 x 100 pixels; resizing a window to be smaller than this minimum
requires signed JavaScript. You need the UniversalBrowserWrite privilege for this. For
information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Examples
To make the current window 5 pixels narrower and 10 pixels taller than its current dimensions, use
this statement:
[Link](-5,10); // relative positioning
See also
[Link]
resizeTo
Resizes an entire window to the specified pixel dimensions.
Method of Window
Syntax
resizeTo(outerWidth, outerHeight)
Parameters
Description
This method changes the window's dimensions by setting its outerWidth and outerHeight
properties. The upper left-hand corner remains anchored and the lower right-hand corner moves.
resizeBy moves to the specified position. The origin of the axes is at absolute position (0,0); this is
the upper left-hand corner of the display.
Security
Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed
JavaScript, so a window won't move past the screen boundaries. In addition, windows have an
enforced minimum size of 100 x 100 pixels; resizing a window to be smaller than this minimum
Page No:200
requires signed JavaScript. You need the UniversalBrowserWrite privilege for this. For
information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Examples
To make the window 225 pixels wide and 200 pixels tall, use this statement:
[Link](225,200); // absolute positioning
See also
[Link]
routeEvent
Passes a captured event along the normal event hierarchy.
Method of Window
Syntax
routeEvent(event)
Parameters
Description
If a subobject (document or layer) is also capturing the event, the event is sent to that object.
Otherwise, it is sent to its original target.
routeEvent works in tandem with captureEvents, releaseEvents, and handleEvent. For more
information, see "Events in Navigator 4.0".
scroll
Scrolls a window to a specified coordinate.
Method of Window
Description
In Navigator 4.0, scroll is no longer used and has been replaced by scrollTo. scrollTo extends
the capabilities of scroll. scroll remains for backward compatibility.
scrollBy
Scrolls the viewing area of a window by the specified amount.
Method of Window
Syntax
scrollBy(horizontal, vertical)
Parameters
horizontal The number of pixels by which to scroll the viewing area horizontally.
vertical The number of pixels by which to scroll the viewing area vertically.
Page No:201
Description
This method scrolls the content in the window if portions that can't be seen exist outside of the
window. scrollBy scrolls the window by adding or subtracting the specified number of pixels to the
current scrolled location.
For this method to have an effect the visible property of [Link] must be true.
Examples
To scroll the current window 5 pixels towards the left and 30 pixels down from the current position,
use this statement:
[Link](-5,30); // relative positioning
See also
[Link]
scrollTo
Scrolls the viewing area of the window so that the specified point becomes the top-left corner.
Method of Window
Syntax
scrollTo(x-coordinate, y-coordinate)
Parameters
Description
The scrollTo method scrolls the content in the window if portions that can't be seen exist outside of
the window. For this method to have an effect the visible property of [Link] must be
true.
Examples
Example 1: Scroll the current viewing area. To scroll the current window to the leftmost boundary
and 20 pixels down from the top of the window, use this statement:
[Link](0,20); // absolute positioning
Example 2: Scroll a different viewing area. The following code, which exists in one frame, scrolls
the viewing area of 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) {
var x = parseInt([Link])
var y = parseInt([Link])
[Link](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>
Page No:202
<BR><INPUT TYPE="button" VALUE="Go"
onClick="scrollIt([Link])">
</FORM>
See also
[Link]
setInterval
Evaluates an expression or calls a function every time a specified number of milliseconds elapses,
until canceled by a call to clearInterval.
Method of Window
Syntax
setInterval(expression, msec)
setInterval(function, msec, arg1, ..., argN)
Parameters
Description
The timeouts continue to fire until the associated window or frame is destroyed or the interval is
canceled using the clearInterval method.
See also
[Link], [Link]
setTimeout
Evaluates an expression or calls a function once after a specified number of milliseconds elapses.
Method of Window
Syntax
setTimeout(expression, msec)
setTimeout(function, msec, arg1, ..., argN)
Parameters
Description
Page No:203
The setTimeout method evaluates an expression or calls a function after a specified amount of time.
It does not act repeatedly. For example, if a setTimeout method specifies five seconds, the
expression is evaluated or the function is called after five seconds, not every five seconds. For
repetitive timeouts, use the setInterval method.
setTimeout does not stall the script. The script continues immediately (not waiting for the timeout to
expire). The call simply schedules an additional future event.
Examples
Example 1. The following example displays an alert message five 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"
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 to 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 = [Link]()
var minutes = [Link]()
var seconds = [Link]()
var timeValue = "" + ((hours > 12) ? hours - 12 : hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
[Link] = 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 ="">
Page No:204
</FORM>
</BODY>
See also
[Link], [Link]
stop
Stops the current download.
Method of Window
Syntax
stop()
Parameters
None
Definition
This method performs the same action as a user choosing the Stop button in the browser.
Chapter 7
Form
This chapter deals with the use of forms, which appear within a document to obtain input from the
user.
Object Description
Button A push button on an HTML form.
Checkbox A checkbox on an HTML form.
FileUpload A file upload element on an HTML form.
Form Lets users input text and make choices from Form elements such as checkboxes,
radio buttons, and selection lists.
Page No:205
Hidden A Text object that is suppressed from form display on an HTML form.
Option A Select object option.
Password A text field on an HTML form that conceals its value by displaying asterisks (*).
Radio A set of radio buttons on an HTML form.
Reset A reset button on an HTML form.
Select A selection list on an HTML form.
Submit A submit button on an HTML form.
Text A text input field on an HTML form.
Textarea A multiline input field on an HTML form.
Button
A push button on an HTML form.
Client-side object
Created by
The HTML INPUT tag, with "button" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates appropriate Button objects and puts these objects in the elements
array of the corresponding Form object. You access a Button object by indexing this array. You can
index the array either by number or, if supplied, by using the value of the NAME attribute.
Event handlers
onBlur
onClick
onFocus
onMouseDown
onMouseUp
Description
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.
Property Summary
Page No:206
form Specifies the form containing the Button object.
name Reflects the NAME attribute.
type Reflects the TYPE attribute.
value Reflects the VALUE attribute.
Method Summary
Examples
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([Link])">
See also
Properties
form
An object reference specifying the form containing the button.
Property of Button
Read-only
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
Examples
Example 1. In the following example, the form myForm contains a Text object and a button. When
the user clicks the button, the value of the Text object is set to the form's name. The button's onClick
event handler uses [Link] to refer to the parent form, myForm.
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="[Link]=[Link]">
</FORM>
Example 2. The following example shows a form with several elements. When the user clicks
button2, the function showElements displays an alert dialog box containing the names of each
element on the form myForm.
function showElements(theForm) {
str = "Form Elements of form " + [Link] + ": \n "
for (i = 0; i < [Link]; i++)
str += [Link][i].name + "\n"
alert(str)
}
</script>
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
Page No:207
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="[Link]=[Link]">
<INPUT NAME="button2" TYPE="button" VALUE="Show Form Elements"
onClick="showElements([Link])">
</FORM>
The alert dialog box displays the following text:
JavaScript Alert:
Form Elements of form myForm:
text1
button1
button2
Example 3. The following example uses an object reference, rather than the this keyword, to refer
to a form. The code returns a reference to myForm, which is a form containing myButton.
[Link]
See also
Form
name
A string specifying the button's name.
Property of Button
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting.
Do not confuse the name property with the label displayed on a button. The value property specifies
the label for the button. The name property is not displayed on the screen; it is used to refer
programmatically to the object.
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 Button 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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][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=[Link]("[Link]
alert([Link])
Page No:208
See also
[Link]
type
For all Button objects, the value of the type property is "button". This property specifies the form
element's type.
Property of Button
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that reflects the button's VALUE attribute.
Property of Button
Read-only Mac and UNIX
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The value property is read-only for Macintosh and UNIX systems. On Windows, you can change
this property.
When a VALUE attribute is not specified in HTML, the value property is an empty string.
Do not confuse the value property with the name property. The name property is not displayed on the
screen; it is used to refer programmatically to the objects.
Examples
The following function evaluates the value property of a group of buttons and displays it in the
msgWindow window:
function valueGetter() {
var msgWindow=[Link]("")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]()
}
This example displays the following values:
Query Submit
Reset
Help
Page No:209
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">
See also
[Link]
Methods
blur
Removes focus from the button.
Method of Button
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
Examples
The following example removes focus from the button element userButton:
[Link]()
This example assumes that the button is defined as
<INPUT TYPE="button" NAME="userButton">
See also
[Link]
click
Simulates a mouse-click on the button, but does not trigger the button's onClick event handler.
Method of Button
Implemented in Navigator 2.0
Syntax
click()
Parameters
None.
Security
Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail
privilege. For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the
JavaScript Guide.
focus
Navigates to the button and gives it focus.
Page No:210
Method of Button
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None.
See also
[Link]
handleEvent
Invokes the handler for the specified event.
Method of Button
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the object has an event handler.
Checkbox
A checkbox on an HTML form. A checkbox is a toggle switch that lets the user set a value on or off.
Client-side
object
Implemented in Navigator 2.0
Navigator 3.0: added type property; added onBlur and onFocus event handlers;
added blur and focus methods.
Navigator 4.0: added handleEvent method.
Created by
The HTML INPUT tag, with "checkbox" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates appropriate Checkbox objects and puts these objects in the
elements array of the corresponding Form object. You access a Checkbox object by indexing this
array. You can index the array either by number or, if supplied, by using the value of the NAME
attribute.
Event handlers
onBlur
onClick
onFocus
Description
Page No:211
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 or
reset.
Property Summary
checked Boolean property that reflects the current state of the checkbox.
defaultChecked Boolean property that reflects the CHECKED attribute.
form Specifies the form containing the Checkbox object.
name Reflects the NAME attribute.
type Reflects the TYPE attribute.
value Reflects the TYPE attribute.
Method Summary
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
user can use the checkbox to choose whether the text fields are converted to uppercase. Each text
field has an onChange event handler that converts the field value to uppercase if the checkbox is
checked. The checkbox has an onClick event handler that converts all fields to uppercase when the
user checks the checkbox.
<HTML>
<HEAD>
<TITLE>Checkbox object example</TITLE>
</HEAD>
<SCRIPT>
function convertField(field) {
Page No:212
if ([Link]) {
[Link] = [Link]()}
}
function convertAllFields() {
[Link] = [Link]()
[Link] = [Link]()
[Link] = [Link]()
}
</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 ([Link]) {convertAllFields()}"
> Convert fields to upper case
</FORM>
</BODY>
</HTML>
See also
Form, Radio
Properties
checked
A Boolean value specifying the selection state of the checkbox.
Property of Checkbox
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
If a checkbox button is selected, the value of its checked property is true; otherwise, it is false.
You can set the checked property at any time. The display of the checkbox button updates
immediately when you set the checked property.
See also
[Link]
defaultChecked
A Boolean value indicating the default selection state of a checkbox button.
Property of Checkbox
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Page No:213
Description
If a checkbox 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 attribute.
You can set the defaultChecked property at any time. The display of the checkbox does not update
when you set the defaultChecked property, only when you set the checked property.
See also
[Link]
form
An object reference specifying the form containing the checkbox.
Property of Checkbox
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
See also
Form
name
A string specifying the checkbox's name.
Property of Checkbox
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
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 Button 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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
Page No:214
[Link]([Link][i].name +
"<BR>")
}
}
type
For all Checkbox objects, the value of the type property is "checkbox". This property specifies the
form element's type.
Property of Checkbox
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that reflects the VALUE attribute of the checkbox.
Property of Checkbox
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
See also
[Link], [Link]
Methods
blur
Removes focus from the checkbox.
Method of Checkbox
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
See also
[Link]
click
Page No:215
Simulates a mouse-click on the checkbox, but does not trigger its onClick event handler. The method
checks the checkbox and sets toggles its value.
Method of Checkbox
Implemented in Navigator 2.0
Syntax
click()
Parameters
None.
Examples
The following example toggles the selection status of the newAge checkbox on the musicForm form:
[Link]()
focus
Gives focus to the checkbox.
Method of Checkbox
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None
Description
Use the focus method to navigate to a the checkbox and give it focus. The user can then toggle the
state of the checkbox.
See also
[Link]
handleEvent
Invokes the handler for the specified event.
Method of Checkbox
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
FileUpload
A file upload element on an HTML form. A file upload element lets the user supply a file as input.
Page No:216
Client-side object
Implemented in Navigator 2.0
Navigator 3.0: added type property
Navigator 4.0: added handleEvent method.
Created by
The HTML INPUT tag, with "file" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates appropriate FileUpload objects and puts these objects in the
elements array of the corresponding Form object. You access a FileUpload object by indexing this
array. You can index the array either by number or, if supplied, by using the value of the NAME
attribute.
Event handlers
onBlur
onChange
onFocus
Description
A FileUpload object is a form element and must be defined within a FORM tag.
Property Summary
Method Summary
Examples
Page No:217
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: ' + [Link])">
<INPUT TYPE="button" VALUE="value"
onClick="alert('value: ' + [Link])"><BR>
</FORM>
See also
Text
Properties
form
An object reference specifying the form containing the object.
Property of FileUpload
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
name
A string specifying the name of this object.
Property of FileUpload
Read-only
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The name property initially reflects the value of the NAME attribute. The name property is not displayed
on-screen; it is used to refer to the objects programmatically.
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 FileUpload 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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
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:
Page No:218
newWindow=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
}
}
type
For all FileUpload objects, the value of the type property is "file". This property specifies the
form element's type.
Property of FileUpload
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that reflects the VALUE attribute of the object.
Property of FileUpload
Read-only
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Navigator 4.0: Setting a file upload widget requires the UniversalFileRead privilege. For information
on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript Guide.
Description
Use the value property to obtain the file name that the user typed into a FileUpload object.
Methods
blur
Removes focus from the object.
Method of FileUpload
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
Page No:219
See also
[Link], [Link]
focus
Navigates to the FileUpload field and give it focus.
Method of FileUpload
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None
See also
[Link], [Link]
handleEvent
Invokes the handler for the specified event.
Syntax
handleEvent(event)
Method of FileUpload
Implemented in Navigator 4.0
Parameters
event The name of an event for which the object has an event handler.
Description
select
Selects the input area of the file upload field.
Method of FileUpload
Implemented in Navigator 2.0
Syntax
select()
Parameters
None
Description
Page No:220
Use the select method to highlight the input area of a file upload field. You can use the select
method with the focus method to highlight a field and position the cursor for a user response. This
makes it easy for the user to replace all the text in the field.
Form
Lets users input text and make choices from Form elements such as checkboxes, radio buttons, and
selection lists. You can also use a form to post data to a server.
Client-side object
Implemented in Navigator 2.0
Navigator 3.0: added reset method.
Navigator 4.0: added handleEvent method.
Created by
The HTML FORM tag. The JavaScript runtime engine creates a Form object for each FORM tag in the
document. You access FORM objects through the [Link] property and through named
properties of that object.
To define a form, use standard HTML syntax with the addition of JavaScript event handlers. If you
supply a value for the NAME attribute, you can use that value to index into the forms array. In
addition, the associated document object has a named property for each named form.
Event handlers
onReset
onSubmit
Description
Each form in a document is a distinct object. You can refer to a form's elements in your code by
using the element's name (from the NAME attribute) or the [Link] array. The elements array
contains an entry for each element (such as a Checkbox, Radio, or Text object) in a form.
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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
Property Summary
Method Summary
Page No:221
Examples
Example 1: Named form. The following example creates a form called myForm that contains text
fields for first name and last name. The form also contains two buttons that change the names to all
uppercase or all lowercase. 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") {
[Link]=[Link]()
[Link]=[Link]()}
else {
[Link]=[Link]()
[Link]=[Link]()}
}
</SCRIPT>
<BODY>
<FORM NAME="myForm">
<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 ' + [Link][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. onSubmit calls a function, checkData, that returns true if there are 3 characters;
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, onSubmit contains a return statement
that returns the value obtained with the function call.
<HTML>
<HEAD>
<TITLE>Form object/onSubmit event handler example</TITLE>
<TITLE>Form object example</TITLE>
</HEAD>
<SCRIPT>
var dataOK=false
function checkData (){
if ([Link] == 3) {
return true}
else {
alert("Enter exactly three characters. " + [Link]
+
" is not valid.")
return false}
}
</SCRIPT>
<BODY>
<FORM NAME="myForm" onSubmit="return checkData()">
<B>Enter 3 characters:</B>
<INPUT TYPE="text" NAME="threeChar" SIZE=3>
<P><INPUT TYPE="submit" VALUE="Done" NAME="submit1"
onClick="[Link]=[Link]
erCase()">
</FORM>
</BODY>
</HTML>
Page No:222
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 ([Link] == 3) {
[Link]()}
else {
alert("Enter exactly three characters. " + [Link]
+
" is not valid.")
return false}
}
</SCRIPT>
<BODY>
<FORM NAME="myForm" 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, FileUpload, Hidden, Password, Radio, Reset, Select, Submit, Text,
Textarea.
Properties
action
A string specifying a destination URL for form data that is submitted
Property of Form
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail
privilege. For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the
JavaScript Guide.
Description
The action property is a reflection of the ACTION attribute of the FORM tag. Each section of a URL
contains different information. See Location for a description of the URL components.
Examples
The following example sets the action property of the musicForm form to the value of the variable
urlName:
[Link]=urlName
Page No:223
See also
elements
An array of objects corresponding to form elements (such as checkbox, radio, and Text objects) in
source order.
Property of Form
Read-only
Implemented in Navigator 2.0
Description
You can refer to a form's elements in your code by using the elements array. This array contains an
entry for each object (Button, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Select,
Submit, Text, or Textarea object) in a form in source order. Each radio button in a Radio object
appears as a separate element in the elements array. For example, if a form called myForm has a text
field and two checkboxes, you can refer to these elements [Link][0],
[Link][1], and [Link][2].
Although you can also refer to a form's elements by using the element's name (from the NAME
attribute), the elements array provides a way to refer to Form objects programmatically 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:
[Link]
[Link][0].value
The value of each element in the elements array is the full HTML statement for the object.
Examples
encoding
A string specifying the MIME encoding of the form.
Property of Form
Implemented in Navigator 2.0
Description
The encoding property initially reflects the ENCTYPE attribute of the FORM tag; however, setting
encoding overrides the ENCTYPE attribute.
Examples
The following function returns the value of the encoding property of musicForm:
function getEncoding() {
return [Link]
}
See also
length
Page No:224
The number of elements in the form.
Property of Form
Read-only
Implemented in Navigator 2.0
Description
The [Link] property tells you how many elements are in the form. You can get the same
information using [Link].
method
A string specifying how form field input information is sent to the server.
Property of Form
Implemented in Navigator 2.0
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".
Examples
The following function returns the value of the musicForm method property:
function getMethod() {
return [Link]
}
See also
name
A string specifying the name of the form.
Property of Form
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
Page No:225
}
}
target
A string specifying the name of the window that responses go to after a form has been submitted.
Property of Form
Implemented in Navigator 2.0
Description
The target property initially reflects the TARGET attribute of the A, AREA, and FORM tags; however,
setting target overrides these attributes.
You can set target using a string, if the string represents a window name. The target property
cannot be assigned the value of a JavaScript expression or variable.
Examples
The following example specifies that responses to the musicInfo form are displayed in the
msgWindow window:
[Link]="msgWindow"
See also
Methods
handleEvent
Invokes the handler for the specified event.
Method of Form
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
Description
reset
Simulates a mouse click on a reset button for the calling form.
Method of Form
Implemented in Navigator 3.0
Syntax
reset()
Parameters
Page No:226
None
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 ([Link] == 'CA' || [Link] == 'AZ') {
alert('Nice input')
}
else { [Link]() }
}
</SCRIPT>
<FORM NAME="myForm" 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, Reset
submit
Submits a form.
Method of Form
Implemented in Navigator 2.0
Syntax
submit()
Parameters
None
Security
Navigator 3.0: The submit method fails without notice if the form's action is a [Link] news:, or
snews: URL. Users can submit forms with such URLs by clicking a submit button, but a confirming
dialog will tell them that they are about to give away private or sensitive information.
Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail
privilege. For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the
JavaScript Guide.
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 [Link].
Page No:227
Examples
Hidden
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.
Client-side object
Implemented in Navigator 2.0
Navigator 3.0: added type property
Created by
The HTML INPUT tag, with "hidden" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates appropriate Hidden objects and puts these objects in the elements
array of the corresponding Form object. You access a Hidden object by indexing this array. You can
index the array either by number or, if supplied, by using the value of the NAME attribute.
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 an end user, but you can programmatically change
the value of the object by changing its value property. You can use Hidden objects for client/server
communication.
Property Summary
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="myForm">
<INPUT TYPE="hidden" NAME="hiddenObject" VALUE="None">
<P>
<INPUT TYPE="button" VALUE="Click me" NAME="button1"
onClick="[Link]=[Link]">
<P>
<INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b"
onClick="[Link]=[Link]"> Soul and R&B
<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"
onClick="[Link]=[Link]"> Jazz
<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"
onClick="[Link]=[Link]"> Classical
Page No:228
<P>
<SELECT NAME="music_type_single"
onFocus="[Link]=[Link][[Link]].t
ext">
<OPTION SELECTED> Red <OPTION> Orange <OPTION> Yellow
</SELECT>
<P><INPUT TYPE="button" VALUE="Display hidden value" NAME="button2"
onClick="alert('Last object clicked: ' + [Link])">
</FORM>
</BODY>
</HTML>
See also
[Link]
Properties
form
An object reference specifying the form containing this object.
Method of Hidden
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
Examples
Example 1. In the following example, the form myForm contains a Hidden object and a button. When
the user clicks the button, the value of the Hidden object is set to the form's name. The button's
onClick event handler uses [Link] to refer to the parent form, myForm.
<FORM NAME="myForm">
Form name:<INPUT TYPE="hidden" NAME="h1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Store Form Name"
onClick="[Link]=[Link]">
</FORM>
Example 2. The following example uses an object reference, rather than the this keyword, to refer
to a form. The code returns a reference to myForm, which is a form containing myHiddenObject.
[Link]
See also
Form
name
A string specifying the name of this object.
Method of Hidden
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Page No:229
type
For all Hidden objects, the value of the type property is "hidden". This property specifies the form
element's type.
Method of Hidden
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that reflects the VALUE attribute of the object.
Method of Hidden
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Examples
The following function evaluates the value property of a group of buttons and displays it in the
msgWindow window:
function valueGetter() {
var msgWindow=[Link]("")
[Link]("The submit button says " +
[Link] + "<BR>")
[Link]("The reset button says " +
[Link] + "<BR>")
[Link]("The hidden field says " +
[Link] + "<BR>")
[Link]()
}
This example displays the following values:
The submit button says Query Submit
The reset button says Reset
The hidden field says pipefish are cute.
The previous example assumes the buttons have been defined as follows:
<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="hidden" NAME="hiddenField" VALUE="pipefish are cute.">
Option
An option in a selection list.
Client-side
object
Implemented in Navigator 2.0
Page No:230
Navigator 3.0: added defaultSelected property; text property can be changed to
change the text of an option
Created by
The Option constructor or the HTML OPTION tag. To create an Option object with its constructor:
new Option(text, value, defaultSelected, selected)
Once you've created an Option object, you can add it to a selection list using the [Link]
array.
Parameters
Property Summary
Description
Usually you work with Option objects in the context of a selection list (a Select object). When
JavaScript creates a Select object for each SELECT tag in the document, it creates Option objects for
the OPTION tags inside the SELECT tag and puts those objects in the options array of the Select
object.
In addition, you can create new options using the Option constructor and add those to a selection list.
After you create an option and add it to the Select object, you must refresh the document by using
[Link](0). This statement must be last. When the document reloads, variables are lost if not
saved in cookies or form element values.
You can use the [Link] and [Link] properties to change the selection
state of an option.
[Link] = i
The [Link] property 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:
[Link][i].selected = true
To change an option's text, use is [Link] property. For example, suppose a form has the
following Select object:
<SELECT name="userChoice">
<OPTION>Choice 1
<OPTION>Choice 2
Page No:231
<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:
[Link][i].text = [Link]
You do not need to reload or refresh after changing an option's text.
Examples
The following example creates two Select objects, one with and one without the MULTIPLE attribute.
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("[Link][i]=option" + i)
if (i==0) {
[Link][i].selected=true
}
}
[Link](0)
}
</SCRIPT>
Properties
defaultSelected
A Boolean value indicating the default selection state of an option in a selection list.
Property of Option
Implemented in Navigator 3.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
If an option 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.
Page No:232
You can set the defaultSelected property at any time. The display of the corresponding Select
object does not update when you set the defaultSelected property of an option, only when you set
the [Link] or [Link] properties.
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 < [Link]; i++) {
if ([Link][i].defaultSelected == true) {
[Link][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
[Link], [Link]
selected
A Boolean value indicating whether an option in a Select object is selected.
Property of Option
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
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 associated Select object
updates immediately when you set the selected property for one of its options.
In general, the [Link] property is more useful than the [Link] property
for Select objects that are created with the MULTIPLE attribute. With the [Link] property,
you can evaluate every option in the [Link] array to determine multiple selections, and you
can select individual options without clearing the selection of other options.
Examples
See also
Page No:233
[Link], [Link]
text
A string specifying the text of an option in a selection list.
Property of Option
Implemented Navigator 2.0
in Navigator 3.0: The text property can be changed to updated the selection option. In
previous releases, you could set the text property but the new value was not reflected
in the Select object.
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The text property initially reflects the text that follows an OPTION tag of a SELECT tag. You can set
the text property at any time and the text displayed by the option in the selection list changes.
Examples
Example 1. 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.
function getChoice() {
for (var i = 0; i < [Link]; i++) {
if ([Link][i].selected == true) {
return [Link][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>
Example 2. In the following form, the user can enter some text in the first text field and then enter a
number between 0 and 2 (inclusive) in the second text field. When the user clicks the button, the text
is substituted for the indicated option number and that option is selected.
<SCRIPT>
function updateList(theForm, i) {
[Link][i].text = [Link]
[Link][i].selected = true
Page No:234
}
</SCRIPT>
<FORM>
<SELECT name="userChoice">
<OPTION>Choice 1
<OPTION>Choice 2
<OPTION>Choice 3
</SELECT>
<BR>
New text for the option: <INPUT TYPE="text" NAME="whatsNew">
<BR>
Option to change (0, 1, or 2): <INPUT TYPE="text" NAME="idx">
<BR>
<INPUT TYPE="button" VALUE="Change Selection"
onClick="updateList([Link], [Link])">
</FORM>
See also
getOptionValue
value
A string that reflects the VALUE attribute of the option.
Property of Option
Read-only
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
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 the empty string. The value property
is not displayed on the screen but is returned to the server if the option is selected.
Do not confuse the property with the selection state of the option or the text that is displayed next to
it. The selected property determines the selection state of the object, and the defaultSelected
property determines the default selection state. The text that is displayed is specified following the
OPTION tag and corresponds to the text property.
Password
A text field on an HTML form that conceals its value by displaying asterisks (*). When the user
enters text into the field, asterisks (*) hide entries from view.
Client-side object
Implemented in Navigator 2.0
Navigator 3.0: added type property; added onBlur and onFocus event handlers
Navigator 4.0: added handleEvent method.
Created by
The HTML INPUT tag, with "password" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates appropriate Password objects and puts these objects in the
elements array of the corresponding Form object. You access a Password object by indexing this
Page No:235
array. You can index the array either by number or, if supplied, by using the value of the NAME
attribute.
Event handlers
onBlur
onFocus
Description
A Password object is a form element and must be defined within a FORM tag.
Security
Navigator 3.0: If a user interactively modifies the value in a password field, you cannot evaluate it
accurately unless data tainting is enabled. See the JavaScript Guide.
Property Summary
Method Summary
Examples
See also
Form, Text
Properties
defaultValue
Page No:236
A string indicating the default value of a Password object.
Property of Password
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The initial value of defaultValue is null (for security reasons), regardless of the value of the VALUE
attribute.
Setting defaultValue programmatically overrides the initial setting. If you programmatically set
defaultValue for the Password object and then evaluate it, JavaScript returns the current value.
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.
See also
[Link]
form
An object reference specifying the form containing this object.
Property of Password
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
name
A string specifying the name of this object.
Property of Password
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting. The name property is not displayed on-screen; it is used to refer to the objects
programmatically.
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 Password element on
the same form have their NAME attribute set to "myField", an array with the elements myField[0],
Page No:237
myField[1],and myField[2] is created. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
}
}
type
For all Password objects, the value of the type property is "password". This property specifies the
form element's type.
Property of Password
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that initially reflects the VALUE attribute.
Property of Password
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security". If you programmatically set the value property and then evaluate it, JavaScript returns the
current value. If a user interactively modifies the value in the password field, you cannot evaluate it
accurately unless data tainting is enabled. See the JavaScript Guide.
Description
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.
See also
[Link]
Methods
blur
Removes focus from the object.
Page No:238
Method of Password
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
Examples
The following example removes focus from the password element userPass:
[Link]()
This example assumes that the password is defined as
<INPUT TYPE="password" NAME="userPass">
See also
[Link], [Link]
focus
Gives focus to the password object.
Method of Password
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None
Description
Use the focus method to navigate to the password field and give it focus. You can then either
programmatically enter a value in the field 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 reenter the password.
function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
[Link]()
[Link]()
}
}
This example assumes that the Password object is defined as
<INPUT TYPE="password" NAME="userPass">
See also
[Link], [Link]
Page No:239
handleEvent
Invokes the handler for the specified event.
Method of Password
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the object has an event handler.
Description
select
Selects the input area of the password field.
Method of Password
Implemented in Navigator 2.0
Syntax
select()
Parameters
None
Description
Use the select method to highlight the input area of the password field. 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 reenter the password.
function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
[Link]()
[Link]()
}
}
This example assumes that the password is defined as
<INPUT TYPE="password" NAME="userPass">
Radio
An individual radio button in a set of radio buttons on an HTML form. The user can use a set of radio
buttons to choose one item from a list.
Client-side object
Implemented in Navigator 2.0
Page No:240
Navigator 3.0: added type property; added blur and focus methods.
Navigator 4.0: added handleEvent method.
Created by
The HTML INPUT tag, with "radio" as the value of the TYPE attribute. All the radio buttons in a
single group must have the same value for the NAME attribute. This allows them to be accessed as a
single group.
For a given form, the JavaScript runtime engine creates an individual Radio object for each radio
button in that form. It puts in a single array all the Radio objects that have the same value for the
NAME attribute. It puts that array in the elements array of the corresponding Form object. If a single
form has multiple sets of radio buttons, the elements array has multiple Radio objects.
You access a set of buttons by accessing the [Link] array (either by number or by using the
value of the NAME attribute). To access the individual radio buttons in that set, you use the returned
object array. For example, if your document has a form called emp with a set of radio buttons whose
NAME attribute is "dept", you would access the individual buttons as [Link][0],
[Link][1], and so on.
Event handlers
onBlur
onClick
onFocus
Description
A Radio object is a form element and must be defined within a FORM tag.
Property Summary
checked Lets you programmatically select a radio button (property of the individual
button).
defaultChecked Reflects the CHECKED attribute (property of the individual button).
form Specifies the form containing the Radio object (property of the array of buttons).
Page No:241
name Reflects the NAME attribute (property of the array of buttons).
type Reflects the TYPE attribute (property of the array of buttons).
value Reflects the VALUE attribute (property of the array of buttons).
Method Summary
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="[Link] = 'soul-and-r&b'"> Soul and R&B
<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"
onClick="[Link] = 'jazz'"> Jazz
<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"
onClick="[Link] = '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 uppercase or lowercase,
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 uppercase and lowercase 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 ([Link][0].checked) {
[Link] = [Link]()}
else {
if ([Link][1].checked) {
[Link] = [Link]()}
}
}
function convertAllFields(caseChange) {
if (caseChange=="upper") {
[Link] = [Link]()
[Link] = [Link]()
[Link] = [Link]()}
else {
[Link] = [Link]()
[Link] = [Link]()
[Link] = [Link]()
}
}
</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"
Page No:242
onClick="if ([Link]) {convertAllFields('upper')}"> Upper case
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="lower"
onClick="if ([Link]) {convertAllFields('lower')}"> Lower case
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="noChange"> No conversion
</FORM>
</BODY>
</HTML>
See also the example for Link.
See also
Properties
checked
A Boolean value specifying the selection state of a radio button.
Property of Radio
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
If a radio button is selected, the value of its checked property is true; otherwise, it is false. You can
set the checked property at any time. The display of the radio button updates immediately when you
set the checked property.
At any given time, only one button in a set of radio buttons can be checked. When you set the
checked property for one radio button in a group to true, that property for all other buttons in the
group becomes false.
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 [Link]) {
if ([Link][i].checked=="1") {
checkedButton=[Link][i].value
}
}
}
See also
[Link]
defaultChecked
A Boolean value indicating the default selection state of a radio button.
Property of Radio
Implemented in Navigator 2.0
Security
Page No:243
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
If a 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 attribute.
Unlike for the checked property, changing the value of defaultChecked for one button in a radio
group does not change its value for the other buttons in the group.
You can set the defaultChecked property at any time. The display of the 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 [Link]) {
if ([Link][i].defaultChecked==true) {
[Link][i].checked=true
}
}
}
See also
[Link]
form
An object reference specifying the form containing the radio button.
Property of Radio
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
name
A string specifying the name of the set of radio buttons with which this button is associated.
Property of Radio
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
Page No:244
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting.
All radio buttons that have the same value for their name property are in the same group and are
treated together. If you change the name of a single radio button, you change which group of buttons
it belongs to.
Do not confuse the name property with the label displayed on a Button. The value property specifies
the label for the button. The name property is not displayed onscreen; it is used to refer
programmatically to the button.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
}
}
type
For all Radio objects, the value of the type property is "radio". This property specifies the form
element's type.
Property of Radio
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that reflects the VALUE attribute of the radio button.
Property of Radio
Read-only
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
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 on the screen but is returned to the server if the radio button or
checkbox is selected.
Page No:245
Do not confuse the property with the selection state of the radio button or the text that is displayed
next to the 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 tag.
Examples
The following function evaluates the value property of a group of radio buttons and displays it in the
msgWindow window:
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]
("The value of radioObj[" + i + "] is " +
[Link][i].value +"<BR>")
}
[Link]()
}
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
[Link], [Link]
Methods
blur
Removes focus from the radio button.
Method of Radio
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
See also
[Link]
click
Simulates a mouse-click on the radio button, but does not trigger the button's onClick event handler.
Method of Radio
Implemented in Navigator 2.0
Syntax
Page No:246
click()
Parameters
None
Examples
The following example toggles the selection status of the first radio button in the musicType Radio
object on the musicForm form:
[Link][0].click()
The following example toggles the selection status of the newAge checkbox on the musicForm form:
[Link]()
focus
Gives focus to the radio button.
Method of Radio
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None
Description
Use the focus method to navigate to the radio button and give it focus. The user can then easily
toggle that button.
See also
[Link]
handleEvent
Invokes the handler for the specified event.
Method of Radio
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
Reset
A reset button on an HTML form. A reset button resets all elements in a form to their defaults.
Client-side
object
Implemented in Navigator 2.0
Page No:247
Navigator 3.0: added type property; added onBlur and onFocus event handlers;
added blur and focus methods
Navigator 4.0: added handleEvent method.
Created by
The HTML INPUT tag, with "reset" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates an appropriate Reset object and puts it in the elements array of
the corresponding Form object. You access a Reset object by indexing this array. You can index the
array either by number or, if supplied, by using the value of the NAME attribute.
Event handlers
onBlur
onClick
onFocus
Description
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.
Property Summary
Method Summary
Page No:248
click Simulates a mouse-click on the reset button.
focus Gives focus to the reset button.
handleEvent Invokes the handler for the specified event.
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">
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
Properties
form
An object reference specifying the form containing the reset button.
Property of Reset
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
See also
Form
Page No:249
name
A string specifying the name of the reset button.
Property of Reset
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The value of the name property initially reflects the value of the NAME attribute. Changing the name
property overrides this setting.
Do not confuse the name property with the label displayed on the reset button. The value property
specifies the label for this button. The name property is not displayed on the screen; it is used to refer
programmatically to the button.
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 Reset 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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
}
}
See also
[Link]
type
For all Reset objects, the value of the type property is "reset". This property specifies the form
element's type.
Property of Reset
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
Page No:250
value
A string that reflects the reset button's VALUE attribute.
Property of Reset
Read-only
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
This string is displayed on the face of the button. When a VALUE attribute is not specified in HTML,
the value property is the string "Reset".
Do not confuse the value property with the name property. The name property is not displayed on the
screen; it is used to refer programmatically to the button.
Examples
The following function evaluates the value property of a group of buttons and displays it in the
msgWindow window:
function valueGetter() {
var msgWindow=[Link]("")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]()
}
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">
See also
[Link]
Methods
blur
Removes focus from the reset button.
Method of Reset
Implemented in Navigator 2.0
Syntax
blur()
Parameters
Page No:251
None
Examples
The following example removes focus from the reset button userReset:
[Link]()
This example assumes that the button is defined as
<INPUT TYPE="reset" NAME="userReset">
See also
[Link]
click
Simulates a mouse-click on the reset button, but does not trigger an object's onClick event handler.
Method of Reset
Implemented in Navigator 2.0
Syntax
click()
Parameters
None
focus
Navigates to the reset button and gives it focus.
Method of Reset
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None
See also
[Link]
handleEvent
Invokes the handler for the specified event.
Method of Reset
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
Page No:252
Select
A selection list on an HTML form. The user can choose one or more items from a selection list,
depending on how the list was created.
Client-side object
Implemented in Navigator 2.0
Navigator 3.0: added type property; added the ability to add and delete options.
Navigator 4.0: added handleEvent method.
Created by
The HTML SELECT tag. For a given form, the JavaScript runtime engine creates appropriate Select
objects for each selection list and puts these objects in the elements array of the corresponding Form
object. You access a Select object by indexing this array. You can index the array either by number
or, if supplied, by using the value of the NAME attribute.
The runtime engine also creates Option objects for each OPTION tag inside the SELECT tag.
Event handlers
onBlur
onChange
onFocus
Description
The following figure shows a form containing two selection lists. The user can choose one item from
the list on the left and can choose multiple items from the list on the right:
A Select object is a form element and must be defined within a FORM tag.
Property Summary
Page No:253
more selected options.
Method Summary
Examples
Example 1. The following example displays two selection lists. In the first list, the user can select
only one item; in the second list, the user can select multiple items.
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>
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=[Link]
dayInteger=[Link]
monthString=[Link][monthInteger].text
dayString=[Link][dayInteger].text
// Display property values
[Link]=monthString + " " + dayString
[Link]=[Link]
[Link]=[Link]
[Link]=[Link]
[Link]=[Link]
[Link]=[Link]
[Link]=[Link]
// Is it Cinco de Mayo?
if ([Link][4].selected && [Link][4].selected)
[Link]="Yes!"
else
[Link]="No"
}
</SCRIPT>
<!--------------->
<FORM NAME="selectForm">
<P><B>Choose a month and day:</B>
Month: <SELECT NAME="monthSelection"
onChange="updatePropertyDisplay(this,[Link])">
<OPTION> January <OPTION> February <OPTION> March
<OPTION> April <OPTION> May <OPTION> June
<OPTION> July <OPTION> August <OPTION> September
Page No:254
<OPTION> October <OPTION> November <OPTION> December
</SELECT>
Day: <SELECT NAME="daySelection"
onChange="updatePropertyDisplay([Link],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="
[Link]=0;
[Link]=0;
updatePropertyDisplay
[Link],[Link])">
New Year's Day
<INPUT TYPE="radio" NAME="dateChoice"
onClick="
[Link]=4;
[Link]=4;
updatePropertyDisplay
([Link],[Link])">
Cinco de Mayo
<INPUT TYPE="radio" NAME="dateC
Example 3. Add an option with the Option constructor. The following example
creates two Select objects, one with and one without the MULTIPLE attribute. 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")
[Link](0)
}
</SCRIPT>
<HR>
<H3>Select-Multiple Option() constructor</H3>
<FORM>
<SELECT NAME="selectTest" multiple></SELECT><P>
<INPUT TYPE="button" VALUE="Populate Select List" onClick="populate([Link])">
</FORM>
Page No:255
function deleteAnItem(theList,itemNo) {
[Link][itemNo]=null
[Link](0)
}
Properties
form
An object reference specifying the form containing the selection list.
Property of Select
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
length
The number of options in the selection list.
Property of Select
Read-only
Implemented in Navigator 2.0
name
A string specifying the name of the selection list.
Property of Select
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see
"JavaScript Security".
Description
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting. The name property is not displayed on the screen; it is used to refer to the list
programmatically.
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 Select 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. You need to be aware of this situation in your code and know
whether myField refers to a single element or to an array of elements.
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:
Page No:256
newWindow=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>") }
}
options
An array corresponding to options in a Select object in source order.
Property of Select
Read-only
Implemented in Navigator 2.0
Description
You can refer to the options of a Select object 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, you can access these options as [Link][0],
[Link][1], and [Link][2].
To obtain the number of options in the selection list, you can use either [Link] or the length
property of the options array. For example, you can get the number of options in the musicStyle
selection list with either of these expressions:
[Link]
[Link]
You can add or remove options from a selection list using this array. To add or replace an option to
an existing Select object, you assign a new Option object to a place in the array. For example, to
create a new Option object called jeans and add it to the end of the selection list named myList, you
could use this code:
To delete an option from a Select object, you set the appropriate index of the options array to null.
Removing an option compresses the options array. For example, assume that myList has 5 elements
in it, the value of the fourth element is "foo", and you execute this statement:
[Link][1] = null
Now, myList has 4 elements in it and the value of the third element is "foo".
After you delete an option, you must refresh the document by using [Link](0). This statement
must be last. When the document reloads, variables are lost if not saved in cookies or form element
values.
You can determine which option in a selection list is currently selected by using either the
selectedIndex property of the options array or of the Select object itself. That is, the following
expressions return the same value:
[Link]
[Link]
Page No:257
For more information about this property, see [Link].
For Select objects that can have multiple selections (that is, the SELECT tag has
the MULTIPLE attribute), the selectedIndex property is not very useful. In this
case, it returns the index of the first selection. To find all the selected
options, you have to loop and test each option individually. For example, to
print a list of all selected options in a selection list named mySelect, you
could use code such as this:
In general, to work with individual options in a selection list, you work with
the appropriate Option object.
selectedIndex
An integer specifying the index of the selected option in a Select object.
Property of Select
Implemented in Navigator 2.0
Security
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.
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.
Examples
function getSelectedIndex() {
return [Link]
}
The previous example assumes that the Select object is similar to the following:
<SELECT NAME="musicType">
<OPTION SELECTED> R&B
Page No:258
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>
type
For all Select objects created with the MULTIPLE keyword, the value of the type
property is "select-multiple". For Select objects created without this keyword,
the value of the type property is "select-one". This property specifies the form
element's type.
Property of Select
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on
a form.
Methods
blur
Removes focus from the selection list.
Method of Select
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
focus
Method of Select
Implemented in Navigator 2.0
Syntax
focus()
Page No:259
Parameters
None
Description
Use the focus method to navigate to a selection list and give it focus. The user
can then make selections from the list.
handleEvent
Invokes the handler for the specified event.
Method of Select
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the object has an event handler.
Submit
A submit button on an HTML form. A submit button causes a form to be submitted.
Client-side
object
Implemented in Navigator 2.0
Navigator 3.0: added type property; added onBlur and onFocus event handlers;
added blur and focus methods
Navigator 4.0: added handleEvent method.
Created by
The HTML INPUT tag, with "submit" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates an appropriate Submit object and puts it in the elements array of
the corresponding Form object. You access a Submit object by indexing this array. You can index the
array either by number or, if supplied, by using the value of the NAME attribute.
Event handlers
onBlur
onClick
onFocus
Security
Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail
privilege. For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the
JavaScript Guide.
Description
Page No:260
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.
Property Summary
Method Summary
Examples
The following example creates a Submit object called submitButton. The text "Done" is displayed
on the face of the button.
<INPUT TYPE="submit" NAME="submitButton" VALUE="Done">
See also the examples for the Form.
See also
Properties
form
An object reference specifying the form containing the submit button.
Property of Submit
Read-only
Implemented in Navigator 2.0
Description
Page No:261
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
Examples
The following example shows a form with several elements. When the user clicks button2, the
function showElements displays an alert dialog box containing the names of each element on the
form myForm.
<SCRIPT>
function showElements(theForm) {
str = "Form Elements of form " + [Link] + ": \n "
for (i = 0; i < [Link]; i++)
str += [Link][i].name + "\n"
alert(str)
}
</SCRIPT>
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="[Link]=[Link]">
<INPUT NAME="button2" TYPE="submit" VALUE="Show Form Elements"
onClick="showElements([Link])">
</FORM>
The alert dialog box displays the following text:
Form Elements of form myForm:
text1
button1
button2
See also
Form
name
A string specifying the submit button's name.
Property of Submit
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting.
Do not confuse the name property with the label displayed on the Submit button. The value property
specifies the label for this button. The name property is not displayed on the screen; it is used to refer
programmatically to the button.
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 Submit 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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
Page No:262
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
}
}
See also
[Link]
type
For all Submit objects, the value of the type property is "submit". This property specifies the form
element's type.
Property of Submit
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that reflects the submit button's VALUE attribute.
Property of Submit
Read-only
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
When a VALUE attribute is specified in HTML, the value property is that string and is displayed on
the face of the button. When a VALUE attribute is not specified in HTML, the value property for the
button is the string "Submit Query."
Do not confuse the value property with the name property. The name property is not displayed on the
screen; it is used to refer programmatically to the button.
Examples
The following function evaluates the value property of a group of buttons and displays it in the
msgWindow window:
function valueGetter() {
var msgWindow=[Link]("")
Page No:263
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]()
}
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">
See also
[Link]
Methods
blur
Removes focus from the submit button.
Method of Submit
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
See also
[Link]
click
Simulates a mouse-click on the submit button, but does not trigger an object's onClick event handler.
Method of Submit
Implemented in Navigator 2.0
Syntax
click()
Parameters
None
focus
Navigates to the submit button and gives it focus.
Method of Submit
Implemented in Navigator 2.0
Page No:264
Syntax
focus()
Parameters
None
See also
[Link]
handleEvent
Invokes the handler for the specified event.
Method of Submit
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
Text
A text input field on an HTML form. The user can enter a word, phrase, or series of numbers in a text
field.
Client-side object
Implemented in Navigator 2.0
Navigator 3.0: added type property.
Navigator 4.0: added handleEvent method.
Created by
The HTML INPUT tag, with "text" as the value of the TYPE attribute. For a given form, the
JavaScript runtime engine creates appropriate Text objects and puts these objects in the elements
array of the corresponding Form object. You access a Text object by indexing this array. You can
index the array either by number or, if supplied, by using the value of the NAME attribute.
To define a Text object, use standard HTML syntax with the addition of JavaScript event handlers.
Event handlers
onBlur
onChange
onFocus
onSelect
Description
Page No:265
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 ([Link]).
Property Summary
Method Summary
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>
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
uppercase.
<FORM NAME="form1">
<BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Anchorage"
SIZE="20" onFocus="[Link]()">
<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="AK" SIZE="2"
onChange="[Link]=[Link]()">
</FORM>
See also the examples for the onBlur, onChange, onFocus, and onSelect.
See also
Properties
defaultValue
A string indicating the default value of a Text object.
Property of Text
Implemented in Navigator 2.0
Page No:266
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The initial value of defaultValue reflects the value of the VALUE attribute. Setting defaultValue
programmatically overrides the initial setting.
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=[Link]("")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]()
}
See also
[Link]
form
An object reference specifying the form containing this object.
Property of Text
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
Examples
Example 1. In the following example, the form myForm contains a Text object and a button. When
the user clicks the button, the value of the Text object is set to the form's name. The button's onClick
event handler uses [Link] to refer to the parent form, myForm.
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="[Link]=[Link]">
</FORM>
Example 2. The following example shows a form with several elements. When the user clicks
button2, the function showElements displays an alert dialog box containing the names of each
element on the form myForm.
Page No:267
function showElements(theForm) {
str = "Form Elements of form " + [Link] + ": \n "
for (i = 0; i < [Link]; i++)
str += [Link][i].name + "\n"
alert(str)
}
</script>
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="[Link]=[Link]">
<INPUT NAME="button2" TYPE="button" VALUE="Show Form Elements"
onClick="showElements([Link])">
</FORM>
The alert dialog box displays the following text:
JavaScript Alert:
Form Elements of form myForm:
text1
button1
button2
Example 3. The following example uses an object reference, rather than the this keyword, to refer
to a form. The code returns a reference to myForm, which is a form containing myTextObject.
[Link]
See also
Form
name
A string specifying the name of this object.
Property of Text
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting. The name property is not displayed on-screen; it is used to refer to the objects
programmatically.
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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
Page No:268
}
}
type
For all Text objects, the value of the type property is "text". This property specifies the form
element's type.
Property of Text
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that reflects the VALUE attribute of the object.
Property of Text
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The value property is a string that initially reflects the VALUE attribute. This string is displayed in the
text field. 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 object updates immediately
when you set the value property.
Examples
The following function evaluates the value property of a group of buttons and displays it in the
msgWindow window:
function valueGetter() {
var msgWindow=[Link]("")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]()
}
This example displays the following:
[Link] is Query Submit
[Link] is Reset
[Link] is Stonefish are dangerous.
The previous example assumes the buttons have been defined as follows:
<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="text" NAME="myText" VALUE="Stonefish are dangerous.">
See also
Page No:269
[Link]
Methods
blur
Removes focus from the text field.
Method of Text
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
Examples
The following example removes focus from the text element userText:
[Link]()
This example assumes that the text element is defined as
<INPUT TYPE="text" NAME="userText">
See also
[Link], [Link]
focus
Navigates to the text field and gives it focus.
Method of Text
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None
Description
Use the focus method to navigate to a text field and give it focus. You can then either
programmatically enter a value in the field or let the user enter a value. If you use this method
without the select method, the cursor is positioned at the beginning of the field.
Example
See also
[Link], [Link]
handleEvent
Page No:270
Invokes the handler for the specified event.
Method of Text
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the specified object has an event handler.
select
Selects the input area of the text field.
Method of Text
Implemented in Navigator 2.0
Syntax
select()
Parameters
None
Description
Use the select method to highlight the input area of a text field. You can use the select method
with the focus method to highlight a field and position the cursor for a user response. This makes it
easy for the user to replace all the text in the field.
Example
The following example uses an onClick event handler to move the focus to a text field and select
that field for changing:
<FORM NAME="myForm">
<B>Last name: </B><INPUT TYPE="text" NAME="lastName" SIZE=20 VALUE="Pigman">
<BR><B>First name: </B><INPUT TYPE="text" NAME="firstName" SIZE=20
VALUE="Victoria">
<BR><BR>
<INPUT TYPE="button" VALUE="Change last name"
onClick="[Link]();[Link]();">
</FORM>
Textarea
A multiline input field on an HTML form. The user can use a textarea field to enter words, phrases,
or numbers.
Client-side object
Implemented in Navigator 2.0
Navigator 3.0: added type property.
Navigator 4.0: added handleEvent method.
Created by
Page No:271
The HTML TEXTAREA tag. For a given form, the JavaScript runtime engine creates appropriate
Textarea objects and puts these objects in the elements array of the corresponding Form object.
You access a Textarea object by indexing this array. You can index the array either by number or, if
supplied, by using the value of the NAME attribute.
To define a text area, use standard HTML syntax with the addition of JavaScript event handlers.
Event handlers
onBlur
onChange
onFocus
onKeyDown
onKeyPress
onKeyUp
onSelect
Description
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
([Link]).
To begin a new line in a Textarea object, you can use a newline character. Although this character
varies from platform to platform (Unix is \n, Windows is \r, and Macintosh is \n), JavaScript checks
for all newline characters before setting a string-valued property and translates them as needed for the
user's platform. You could also enter a newline character programmatically--one way is to test the
[Link] property to determine the current platform, then set the newline character
accordingly. See [Link] for an example.
Property Summary
Page No:272
type Specifies that the object is a Textarea object.
value Reflects the current value of the Textarea object.
Method Summary
Examples
Example 1. The following example creates a Textarea object that is six 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>
Example 2. The following example creates a string variable containing newline characters for
different platforms. When the user clicks the button, the Textarea object is populated with the value
from the string variable. The result is three lines of text in the Textarea object.
<SCRIPT>
myString="This is line one.\nThis is line two.\rThis is line three."
</SCRIPT>
<FORM NAME="form1">
<INPUT TYPE="button" Value="Populate the textarea"
onClick="[Link]=myString">
<P>
<TEXTAREA NAME="textarea1" ROWS=6 COLS=55></TEXTAREA>
See also
Properties
defaultValue
A string indicating the default value of a Textarea object.
Property of Textarea
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The initial value of defaultValue reflects the value specified between the TEXTAREA start and end
tags. Setting defaultValue programmatically overrides the initial setting.
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
Page No:273
The following function evaluates the defaultValue property of objects on the surfCity form and
displays the values in the msgWindow window:
function defaultGetter() {
msgWindow=[Link]("")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]()
}
See also
[Link]
form
An object reference specifying the form containing this object.
Property of Textarea
Read-only
Implemented in Navigator 2.0
Description
Each form element has a form property that is a reference to the element's parent form. This property
is especially useful in event handlers, where you might need to refer to another element on the current
form.
Examples
Example 1. The following example shows a form with several elements. When the user clicks
button2, the function showElements displays an alert dialog box containing the names of each
element on the form myForm.
function showElements(theForm) {
str = "Form Elements of form " + [Link] + ": \n "
for (i = 0; i < [Link]; i++)
str += [Link][i].name + "\n"
alert(str)
}
</script>
<FORM NAME="myForm">
Form name:<INPUT TYPE="textarea" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="[Link]=[Link]">
<INPUT NAME="button2" TYPE="button" VALUE="Show Form Elements"
onClick="showElements([Link])">
</FORM>
The alert dialog box displays the following text:
JavaScript Alert:
Form Elements of form myForm:
text1
button1
button2
Example 2. The following example uses an object reference, rather than the this keyword, to refer
to a form. The code returns a reference to myForm, which is a form containing myTextareaObject.
[Link]
See also
Form
Page No:274
name
A string specifying the name of this object.
Property of Textarea
Implemented in Navigator 2.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The name property initially reflects the value of the NAME attribute. Changing the name property
overrides this setting. The name property is not displayed on-screen; it is used to refer to the objects
programmatically.
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. You need to be aware of this situation in your code and
know whether myField refers to a single element or to an array of elements.
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=[Link]("[Link]
function valueGetter() {
var msgWindow=[Link]("")
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i].name +
"<BR>")
}
}
type
For all Textarea objects, the value of the type property is "textarea". This property specifies the
form element's type.
Property of Textarea
Read-only
Implemented in Navigator 3.0
Examples
The following example writes the value of the type property for every element on a form.
for (var i = 0; i < [Link]; i++) {
[Link]("<BR>type is " + [Link][i].type)
}
value
A string that initially reflects the VALUE attribute.
Property of Textarea
Implemented in Navigator 2.0
Page No:275
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
This string is displayed in the textarea field. 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 Textarea object updates immediately
when you set the value property.
Examples
The following function evaluates the value property of a group of buttons and displays it in the
msgWindow window:
function valueGetter() {
var msgWindow=[Link]("")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]("[Link] is " +
[Link] + "<BR>")
[Link]()
}
This example displays the following:
[Link] is Query Submit
[Link] is Reset
[Link] is Tropical waters contain all sorts of cool fish,
such as the harlequin ghost pipefish, dragonet, and cuttlefish.
A cuttlefish looks much like a football wearing a tutu and a mop.
The previous example assumes the buttons have been defined as follows:
<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<TEXTAREA NAME="blurb" rows=3 cols=60>
Tropical waters contain all sorts of cool fish,
such as the harlequin ghost pipefish, dragonet, and cuttlefish.
A cuttlefish looks much like a football wearing a tutu and a mop.
</TEXTAREA>
See also
[Link]
Methods
blur
Removes focus from the object.
Method of Textarea
Implemented in Navigator 2.0
Syntax
blur()
Parameters
None
Examples
Page No:276
The following example removes focus from the textarea element userText:
[Link]()
This example assumes that the textarea is defined as
<TEXTAREA NAME="userText">
Initial text for the text area.
</TEXTAREA>
See also
[Link], [Link]
focus
Navigates to the textarea field and gives it focus.
Method of Textarea
Implemented in Navigator 2.0
Syntax
focus()
Parameters
None
Description
Use the focus method to navigate to the textarea field and give it focus. You can then either
programmatically enter a value in the field or let the user enter a value. If you use this method
without the select method, the cursor is positioned at the beginning of the field.
See also
[Link], [Link]
Example
handleEvent
Invokes the handler for the specified event.
Method of Textarea
Implemented in Navigator 4.0
Syntax
handleEvent(event)
Parameters
event The name of an event for which the object has an event handler.
Description
select
Page No:277
Selects the input area of the object.
Method of Textarea
Implemented in Navigator 2.0
Syntax
select()
Parameters
None
Description
Use the select method to highlight the input area of a textarea field. You can use the select method
with the focus method to highlight the field and position the cursor for a user response. This makes it
easy for the user to replace all the text in the field.
Example
The following example uses an onClick event handler to move the focus to a textarea field and select
that field for changing:
<FORM NAME="myForm">
<B>Last name: </B><INPUT TYPE="text" NAME="lastName" SIZE=20 VALUE="Pigman">
<BR><B>First name: </B><INPUT TYPE="text" NAME="firstName" SIZE=20
VALUE="Victoria">
<BR><B>Description:</B>
<BR><TEXTAREA NAME="desc" ROWS=3 COLS=40>An avid scuba diver.</TEXTAREA>
<BR><BR>
<INPUT TYPE="button" VALUE="Change description"
onClick="[Link]();[Link]();">
</FORM>
Chapter 8
Browser
This chapter deals with the browser and elements associated with it.
Object Description
navigator Contains information about the version of Navigator in use.
MimeType Represents a MIME type (Multipart Internet Mail Extension) supported by the client.
Plugin Represents a plug-in module installed on the client.
navigator
Contains information about the version of Navigator in use.
Client-side
object
Page No:278
Implemented in Navigator 2.0
Navigator 3.0: added mimeTypes and plugins properties; added javaEnabled and
taintEnabled methods.
Navigator 4.0: added language and platform properties; added preference
method.
Created by
The JavaScript runtime engine on the client automatically creates the navigator object.
Description
Use the navigator object to determine which version of the Navigator your users have, what MIME
types the user's Navigator can handle, and what plug-ins the user has installed. All of the properties
of the navigator object are read-only.
Property Summary
Method Summary
Properties
appCodeName
A string specifying the code name of the browser.
Property of navigator
Read-only
Implemented in Navigator 2.0
Examples
appName
A string specifying the name of the browser.
Property of navigator
Read-only
Page No:279
Implemented in Navigator 2.0
Examples
appVersion
A string specifying version information for the Navigator.
Property of navigator
Read-only
Implemented in Navigator 2.0
Description
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.1.
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.
Examples
Example 1. The following example displays version information for the Navigator:
[Link]("The value of [Link] is " +
[Link])
For Navigator 2.0 on Windows 95, this displays the following:
The value of [Link] is 2.0 (Win95, I)
For Navigator 3.0 on Windows NT, this displays the following:
The value of [Link] is 3.0 (WinNT, 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 ([Link]('Win') != -1)
newline="\r\n"
else newline="\n"
[Link]="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([Link])">
</TEXTAREA>
</FORM>
Page No:280
language
Indicates the translation of the Navigator being used.
Property of navigator
Read-only
Implemented in Navigator 4.0
Description
The value for language is usually a 2-letter code, such as "en" and occasionally a five-character code
to indicate a language subtype, such as "zh_CN".
Use this property to determine the language of the Navigator client software being used. For example
you might want to display translated text for the user.
mimeTypes
An array of all MIME types supported by the client.
Property of navigator
Read-only
Implemented in Navigator 3.0
The mimeTypes array contains an entry for each MIME type supported by the client (either internally,
via helper applications, or by plug-ins). For example, if a client supports three MIME types, these
MIME types are reflected as [Link][0], [Link][1], and
[Link][2].
See also
MimeType
platform
Indicates the machine type for which the Navigator was compiled.
Property of navigator
Read-only
Implemented in Navigator 4.0
Description
Platform values are Win32, Win16, Mac68k, MacPPC and various Unix.
The machine type the Navigator was compiled for may differ from the actual machine type due to
version differences, emulators, or other reasons.
If you use SmartUpdate to download software to a user's machine, you can use this property to ensure
that the trigger downloads the appropriate JAR files. The triggering page checks the Navigator
version before checking the platform property. For information on using SmartUpdate, see Using
JAR Installation Manager for SmartUpdate.
plugins
An array of all plug-ins currently installed on the client.
Property of navigator
Page No:281
Read-only
Implemented in Navigator 3.0
You can refer to the Plugin objects installed on the client by using this array. Each element of the
plugins array is a Plugin object. For example, if three plug-ins are installed on the client, these
plug-ins are reflected as [Link][0], [Link][1], and
[Link][2].
1. [Link][index]
2. [Link][index][mimeTypeIndex]
index is an integer representing a plug-in installed on the client or a string containing the name of a
Plugin object (from the name property). The first form returns the Plugin object stored at the
specified location in the plugins array. The second form returns the MimeType object at the specified
index in that Plugin object.
To obtain the number of plug-ins installed on the client, use the length property:
[Link].
[Link]: The plugins array has its own method, refresh. This method makes newly
installed plug-ins available, updates related arrays such as the plugins array, and optionally reloads
open documents that contain plug-ins. You call this method with one of the following statements:
[Link](true)
[Link](false)
If you supply true, refresh refreshes the plugins array to make newly installed plug-ins available
and reloads all open documents that contain embedded objects (EMBED tag). If you supply false, it
refreshes the plugins array, but does not reload open documents.
When the user installs a plug-in, that plug-in is not available until refresh is called or the user closes
and restarts Navigator.
Examples
The following code refreshes arrays and reloads open documents containing embedded objects:
[Link](true)
See also the examples for the Plugin object.
userAgent
A string representing the value of the user-agent header sent in the HTTP protocol from client to
server.
Property of navigator
Read-only
Implemented in Navigator 2.0
Description
Servers use the value sent in the user-agent header to identify the client.
Examples
Page No:282
Methods
javaEnabled
Tests whether Java is enabled.
Method of navigator
Static
Implemented in Navigator 3.0
Syntax
javaEnabled()
Parameters
None.
Description
javaEnabled returns true if Java is enabled; otherwise, false. The user can enable or disable Java by
through user preferences.
Examples
The following code executes function1 if Java is enabled; otherwise, it executes function2.
if ([Link]()) {
function1()
}
else function2()
See also
preference
Allows a signed script to get and set certain Navigator preferences.
Method of navigator
Static
Implemented in Navigator 4.0
Syntax
preference(prefName)
preference(prefName, setValue)
Parameters
prefName A string representing the name of the preference you want to get or set. Allowed
preferences are listed below.
setValue The value you want to assign to the preference. This can be a string, number, or Boolean.
Description
This method returns the value of the preference. If you use the method to set the value, it returns the
new value.
Security
Page No:283
Reading a preference with the preference method requires the UniversalPreferencesRead
privilege. Setting a preference with this method requires the UniversalPreferencesWrite privilege.
For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
With permission, you can get and set the preferences shown in Table 8.2.
taintEnabled
Specifies whether data tainting is enabled.
Method of navigator
Static
Implemented in Navigator 3.0; removed in Navigator 4.0
Syntax
[Link]()
Description
Tainting prevents other scripts from passing information that should be secure and private, such as
directory structures or user session history. JavaScript cannot pass tainted values on to any server
without the end user's permission.
Use taintEnabled to determine if data tainting is enabled. taintEnabled returns true if data
tainting is enabled, false otherwise. The user enables or disables data tainting by using the
environment variable NS_ENABLE_TAINT.
Examples
The following code executes function1 if data tainting is enabled; otherwise it executes function2.
if ([Link]()) {
function1()
}
else function2()
MimeType
Page No:284
A MIME type (Multipart Internet Mail Extension) supported by the client.
Client-side object
Implemented in Navigator 3.0
Created by
You do not create MimeType objects yourself. These objects are predefined JavaScript objects that
you access through the mimeTypes array of the navigator or Plugin object:
[Link][index]
where index is either an integer representing a MIME type supported by the client or a string
containing the type of a MimeType object (from the [Link] property).
Description
Each MimeType object is an element in a mimeTypes array. The mimeTypes array is a property of both
navigator and Plugin objects. For example, the following table summarizes the values for
displaying JPEG images:
Expression Value
[Link]["image/jpeg"].type image/jpeg
[Link]["image/jpeg"].description JPEG Image
[Link]["image/jpeg"].suffixes jpeg, jpg, jpe, jfif, pjpeg, pjp
[Link]["image/jpeg"].enabledPlugins null
Property Summary
Methods
None.
Examples
The following code displays the type, description, suffixes, and enabledPlugin properties for
each MimeType object on a client:
[Link]("<TABLE BORDER=1><TR VALIGN=TOP>",
"<TH ALIGN=left>i",
"<TH ALIGN=left>type",
"<TH ALIGN=left>description",
"<TH ALIGN=left>suffixes",
"<TH ALIGN=left>[Link]</TR>")
for (i=0; i < [Link]; i++) {
[Link]("<TR VALIGN=TOP><TD>",i,
"<TD>",[Link][i].type,
"<TD>",[Link][i].description,
"<TD>",[Link][i].suffixes)
if ([Link][i].enabledPlugin==null) {
[Link](
"<TD>None",
"</TR>")
} else {
[Link](
"<TD>",[Link][i].[Link],
"</TR>")
}
}
[Link]("</TABLE>")
The preceding example displays output similar to the following:
i type description suffixes [Link]
Page No:285
0 audio/aiff AIFF aif, aiff LiveAudio
1 audio/wav WAV wav LiveAudio
2 audio/x-midi MIDI mid, midi LiveAudio
3 audio/midi MIDI mid, midi LiveAudio
4 video/msvideo Video for Windows avi NPAVI32 Dynamic Link
Library
5* Netscape Default Netscape Default Plugin
Plugin
6 zz-application/zz-winassoc- TGZ None
TGZ
See also
Properties
description
A human-readable description of the data type described by the MIME type object.
Property of MimeType
Read-only
Implemented in Navigator 3.0
enabledPlugin
The Plugin object for the plug-in that is configured for the specified MIME type If the MIME type
does not have a plug-in configured, enabledPlugin is null.
Property of MimeType
Read-only
Implemented in Navigator 3.0
Description
Use the enabledPlugin property to determine which plug-in is configured for a specific MIME type.
Each plug-in may support multiple MIME types, and each MIME type could potentially be supported
by multiple plug-ins. However, only one plug-in can be configured for a MIME type. (On Macintosh
and Unix, the user can configure the handler for each MIME type; on Windows, the handler is
determined at browser start-up time.)
The enabledPlugin property is a reference to a Plugin object that represents the plug-in that is
configured for the specified MIME type.
You might need to know which plug-in is configured for a MIME type, for example, to dynamically
emit an EMBED tag on the page if the user has a plug-in configured for the MIME type.
Examples
The following example determines whether the Shockwave plug-in is installed. If it is, a movie is
displayed.
// Can we display Shockwave movies?
mimetype = [Link]["application/x-director"]
if (mimetype) {
// Yes, so can we display with a plug-in?
plugin = [Link]
if (plugin)
// Yes, so show the data in-line
[Link]("Here\'s a movie: <EMBED SRC=[Link] HEIGHT=100
WIDTH=100>")
Page No:286
else
// No, so provide a link to the data
[Link]("<A HREF='[Link]'>Click here</A> to see a movie.")
} else {
// No, so tell them so
[Link]("Sorry, can't show you this cool movie.")
}
suffixes
A string listing possible file suffixes (also known as filename extensions) for the MIME type.
Property of MimeType
Read-only
Implemented in Navigator 3.0
Description
The suffixes property is a string consisting of each valid suffix (typically three letters long)
separated by commas. For example, the suffixes for the "audio/x-midi" MIME type are "mid,
midi".
type
A string specifying the name of the MIME type. This string distinguishes the MIME type from all
others; for example "video/mpeg" or "audio/x-wav".
Property of MimeType
Read-only
Implemented in Navigator 3.0
Property of
MimeType
Plugin
A plug-in module installed on the client.
Client-side object
Implemented in Navigator 3.0
Created by
Plugin objects are predefined JavaScript objects that you access through the [Link]
array.
Description
A Plugin object is a plug-in installed on the client. A plug-in is a software module that the browser
can invoke to display specialized types of embedded data within the browser. The user can obtain a
list of installed plug-ins by choosing About Plug-ins from the Help menu.
Each Plugin object is itself array containing one element for each MIME type supported by the plug-
in. Each element of the array is a MimeType object. For example, the following code displays the
type and description properties of the first Plugin object's first MimeType object.
myPlugin=[Link][0]
myMimeType=myPlugin[0]
[Link]('[Link] is ',[Link],"<BR>")
[Link]('[Link] is ',[Link])
The preceding code displays output similar to the following:
Page No:287
[Link] is video/quicktime
[Link] is QuickTime for Windows
The Plugin object lets you dynamically determine which plug-ins are installed on the client. You can
write scripts to display embedded plug-in data if the appropriate plug-in is installed, or display some
alternative information such as images or text if not.
Plug-ins can be platform dependent and configurable, so a Plugin object's array of MimeType objects
can vary from platform to platform, and from user to user.
When you use the EMBED tag to generate output from a plug-in application, you are not creating a
Plugin object. Use the [Link] array to refer to plug-in instances created with EMBED tags.
See the [Link] array.
Property Summary
Examples
Example 1. The user can obtain a list of installed plug-ins by choosing About Plug-ins from the Help
menu. To see the code the browser uses for this report, choose About Plug-ins from the Help menu,
then choose Page Source from the View menu.
Example 2. The following code assigns shorthand variables for the predefined LiveAudio properties.
Page No:288
plugins\[Link] v.1.0.0
1 LiveAudio d:\nettools\netscape\nav30\Program\ LiveAudio - Netscape 7
plugins\[Link] Navigator sound playing
component
2 NPAVI32 Dynamic d:\nettools\netscape\nav30\Program\ NPAVI32, avi plugin DLL 2
Link Library plugins\[Link]
3 Netscape Default d:\nettools\netscape\nav30\Program\ Null Plugin 1
Plugin plugins\[Link]
Properties
description
A human-readable description of the plug-in. The text is provided by the plug-in developers.
Property of Plugin
Read-only
Implemented in Navigator 3.0
filename
The name of a plug-in file on disk.
Property of Plugin
Read-only
Implemented in Navigator 3.0
Description
The filename property is the plug-in program's file name and is supplied by the plug-in itself. This
name may vary from platform to platform.
Examples
length
The number of elements in the plug-in's array of MimeType objects.
Property of Plugin
Read-only
Implemented in Navigator 3.0
name
A string specifying the plug-in's name.
Property of Plugin
Read-only
Implemented in Navigator 3.0
Security
Navigator 3.0: This property is tainted by default. For information on data tainting, see "JavaScript
Security".
Description
The plug-in's name, supplied by the plug-in itself. Each plug-in should have a name that uniquely
identifies it.
Page No:289
Chapter 9
Events and Event Handlers
This chapter contains the event object and the event handlers that are used with client-side objects in
JavaScript to evoke particular actions. In addition, it contains general information about using events
and event handlers.
Object Description
event Represents a JavaScript event. Passed to every event handler.
Page No:290
text field or moving the mouse over a link. For your script to react to an event, you define event
handlers, such as onChange and onClick.
If an event applies to an HTML tag, then you can define an event handler for it. The name of an event
handler is the name of the event, preceded by "on". For example, the event handler for the focus
event is onFocus.
To create an event handler for an HTML tag, add an event handler attribute to the tag. Put JavaScript
code in quotation marks as the attribute value. The general syntax is
When you create an event handler, the corresponding JavaScript object gets a property with the name
of the event handler in lower case letters. (In Navigator 4.0, you can also use the mixed case name of
the event handler for the property name.) This property allows you to access the object's event
handler. For example, in the preceding example, JavaScript creates a Button object with an onclick
property whose value is "compute([Link])".
Chapter 7, "JavaScript Security," in JavaScript Guide contains more information about creating and
using event handlers.
In Navigator 4.0, JavaScript includes event objects as well as event handlers. Each event has an
event object associated with it. The event object provides information about the event, such as the
type of event and the location of the cursor at the time of the event. When an event occurs, and if an
event handler has been written to handle the event, the event object is sent as an argument to the
event handler.
Typically, the object on which the event occurs handles the event. For example, when the user clicks
a button, it is often the button's event handler that handles the event. Sometimes you may want the
Window or document object to handle certain types of events. For example, you may want the
document object to handle all MouseDown events no matter where they occur in the document.
JavaScript's event capturing model allows you to define methods that capture and handle events
before they reach their intended target.
In addition to providing the event object, Navigator 4.0 allows a Window or document to capture and
handle an event before it reaches its intended target. To accomplish this, the Window, document, and
Layer objects have these new methods:
captureEvents
releaseEvents
routeEvent
handleEvent (Not a method of the Layer object)
For example, suppose you want to capture all click events that occur in a window. First, you need to
set up the window to capture click events:
[Link]([Link]);
Page No:291
The argument to [Link] is a property of the event object and indicates the type of
event to capture. To capture multiple events, the argument is a list separated by vertical slashes (|).
For example:
[Link]([Link] | [Link] | [Link])
Next, you need to define a function that handles the event. The argument evnt is the event object for
the event.
function clickHandler(evnt) {
//What goes here depends on how you want to handle the event.
//This is described below.
}
You have four options for handling the event:
Return true. In the case of a link, the link is followed and no other event handler is checked. If
the event cannot be canceled, this ends the event handling for that event.
Return false. In the case of a link, the link is not followed. If the event is non-cancelable, this
ends the event handling for that event.
Call routeEvent. JavaScript looks for other event handlers for the event. If another object is
attempting to capture the event (such as the document), JavaScript calls its event handler. If
no other object is attempting to capture the event, JavaScript looks for an event handler for the
event's original target (such as a button). The routeEvent method returns the value returned
by the event handler. The capturing object can look at this return value and decide how to
proceed.
function clickHandler(evnt) {
var retval = routeEvent(evnt);
if (retval == false) return false;
else return true;
}
Note: When routeEvent calls an event handler, the event handler is activated. If routeEvent
calls an event handler whose function is to display a new page, the action takes place without
returning to the capturing object.
Call the handleEvent method of an event receiver. Any object that can register event
handlers is an event receiver. This method explicitly calls the event handler of the event
receiver and bypasses the capturing hierarchy. For example, if you wanted all click events to
go to the first link on the page, you could use:
function clickHandler(evnt) {
[Link][0].handleEvent(evnt);
}
As long as the link has an onClick handler, the link handles any click event it receives.
Finally, you need to register the function as the window's event handler for that event:
[Link] = clickHandler;
Important
If a window with frames wants to capture events in pages loaded from different locations, you need
to use captureEvents in a signed script and call [Link].
In the following example, the window and document capture and release events:
<HTML>
<SCRIPT>
function fun1(evnt) {
alert ("The window got an event of type: " + [Link] +
" and will call routeEvent.");
Page No:292
[Link](evnt);
alert ("The window returned from routeEvent.");
return true;
}
function fun2(evnt) {
alert ("The document got an event of type: " + [Link]);
return false;
}
function setWindowCapture() {
[Link]([Link]);
}
function releaseWindowCapture() {
[Link]([Link]);
}
function setDocCapture() {
[Link]([Link]);
}
function releaseDocCapture() {
[Link]([Link]);
}
[Link]=fun1;
[Link]=fun2;
</SCRIPT>
...
</HTML>
event
The event object contains properties that describe a JavaScript event, and is passed as an argument to
an event handler when the event occurs.
Client-side object
Implemented in Navigator 4.0
In the case of a mouse-down event, for example, the event object contains the type of event (in this
case MouseDown), the x and y position of the cursor at the time of the event, a number representing
the mouse button used, and a field containing the modifier keys (Control, Alt, Meta, or Shift) that
were depressed at the time of the event. The properties used within the event object vary from one
type of event to another. This variation is provided in the descriptions of individual event handlers.
Created by
event objects are created by Communicator when an event occurs. You do not create them yourself.
Security
Setting any property of this object requires the UniversalBrowserWrite privilege. In addition,
getting the data property of the DragDrop event requires the UniversalBrowserRead privilege. For
information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Property Summary
Not all of these properties are relevant to each event type. To learn which properties are used by an
event, see the "Event object properties used" section of the individual event handler.
target String representing the object to which the event was originally sent. (All events)
type String representing the event type. (All events)
data Returns an array of strings containing the URLs of the dropped objects. Passed with the
DragDrop event.
height Represents the height of the window or frame.
layerX Number specifying either the object width when passed with the resize event, or the
cursor's horizontal position in pixels relative to the layer in which the event occurred.
Page No:293
Note that layerX is synonymous with x.
layerY Number specifying either the object height when passed with the resize event, or the
cursor's vertical position in pixels relative to the layer in which the event occurred. Note
that layerY is synonymous with y.
modifiers String specifying the modifier keys associated with a mouse or key event. Modifier key
values are: ALT_MASK, CONTROL_MASK, SHIFT_MASK, and META_MASK.
pageX Number specifying the cursor's horizontal position in pixels, relative to the page.
pageY Number specifying the cursor's vertical position in pixels relative to the page.
screenX Number specifying the cursor's horizontal position in pixels, relative to the screen.
screenY Number specifying the cursor's vertical position in pixels, relative to the screen.
which Number specifying either the mouse button that was pressed or the ASCII value of a
pressed key. For a mouse, 1 is the left button, 2 is the middle button, and 3 is the right
button.
width Represents the width of the window or frame.
Example
The following example uses the event object to provide the type of event to the alert message.
<A HREF="[Link] onClick='alert("Link got an event: "
+ [Link])'>Click for link event</A>
The following example uses the event object in an explicitly called event handler.
<SCRIPT>
function fun1(evnt) {
alert ("Document got an event: " + [Link]);
alert ("x position is " + [Link]);
alert ("y position is " + [Link]);
if ([Link] & Event.ALT_MASK)
alert ("Alt key was down for event.");
return true;
}
[Link] = fun1;
</SCRIPT>
onAbort
Executes JavaScript code when an abort event occurs; that is, when the user aborts the loading of an
image (for example by clicking a link or clicking the Stop button).
Event handler for Image
Implemented in Navigator 3.0
Syntax
onAbort="handlerText"
Parameters
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="[Link]"
onAbort="alert('You didn\'t get to see the image!')">
Page No:294
onBlur
Executes JavaScript code when a blur event occurs; that is, when a form element loses focus or when
a window or frame loses focus.
Event handler Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit,
for Text, Textarea, Window
Implemented in Navigator 2.0
Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame, Password,
Radio, Reset, Submit, and Window
Syntax
onBlur="handlerText"
Parameters
Description
The blur event can result from a call to the [Link] method or from the user clicking the
mouse on another object or window or tabbing with the keyboard.
For windows, frames, and framesets, onBlur 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.
Examples
Example 1: Validate form input. 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([Link])">
Example 2: 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="[Link]='lightgrey'"
onFocus="[Link]='antiquewhite'">
Example 3: Change the background color of a frame. The following example creates four frames.
The source for each frame, [Link] has the BODY tag with the onBlur and onFocus event
handlers shown in Example 1. When the document loads, all frames are light grey. When the user
clicks a frame, the onFocus event handler changes the frame's background color to antique white.
The frame that loses focus is changed to light grey. 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=[Link] NAME="frame1">
<FRAME SRC=[Link] NAME="frame2">
Page No:295
<FRAME SRC=[Link] NAME="frame3">
<FRAME SRC=[Link] 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.
<SCRIPT>
function setUpHandlers() {
for (var i = 0; i < [Link]; i++) {
frames[i].onfocus=new Function("[Link]='antiquewhite'")
frames[i].onblur=new Function("[Link]='lightgrey'")
}
}
</SCRIPT>
<FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad=setUpHandlers()>
<FRAME SRC=[Link] NAME="frame1">
<FRAME SRC=[Link] NAME="frame2">
<FRAME SRC=[Link] NAME="frame3">
<FRAME SRC=[Link] NAME="frame4">
</FRAMESET>
Example 4: Close a window. In the following example, a window's onBlur event handler closes the
window when the window loses focus.
<BODY onBlur="[Link]()">
This is some text
</BODY>
onChange
Executes JavaScript code when a change event occurs; that is, when a Select, Text, or Textarea
field loses focus and its value has been modified.
Event handler for FileUpload, Select, Text, Textarea
Implemented in Navigator 2.0 event handler for Select, Text, and Textarea
Navigator 3.0: added as event handler of FileUpload
Syntax
onChange="handlerText"
Parameters
Description
Examples
In the following example, userName is a text field. When a user changes the text and leaves the field,
the onChange event handler calls the checkValue function to confirm that userName has a legal
value.
<INPUT TYPE="text" VALUE="" NAME="userName"
onChange="checkValue([Link])">
onClick
Page No:296
Executes JavaScript code when a click event occurs; that is, when an object on a form is clicked. (A
Click event is a combination of the MouseDown and MouseUp events).
Event handler Button, document, Checkbox, Link, Radio, Reset, Submit
for
Implemented in Navigator 2.0
Navigator 3.0: added the ability to return false to cancel the action associated with a
click event
Syntax
onClick="handlerText"
Parameters
Description
For checkboxes, links, radio buttons, reset buttons, and submit buttons, onClick can return false to
cancel the action normally associated with a click event.
For example, the following code creates a link that, when clicked, displays a confirm dialog box. If
the user clicks the link and then chooses cancel, the page specified by the link is not loaded.
Examples
Example 1: Call a function when a user clicks a button. 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([Link])">
In the preceding example, the keyword this refers to the current object; in this case, the Calculate
button. The construct [Link] refers to the form containing the button.
Page No:297
For another example, suppose you have created a JavaScript function called pickRandomURL that lets
you select a URL at random. You can use onClick to specify a value for the HREF attribute of the A
tag dynamically, as shown in the following example:
<A HREF=""
onClick="[Link]=pickRandomURL()"
onMouseOver="[Link]='Pick a random URL'; return true">
Go!</A>
In the above example, onMouseOver specifies a custom message for the browser's status bar when the
user places the mouse pointer over the Go! anchor. As this example shows, you must return true to
set the [Link] property in the onMouseOver event handler.
Example 2: Cancel the checking of a checkbox. The following example creates a checkbox with
onClick. The event handler displays a confirm that warns the user that checking the checkbox purges
all files. If the user chooses Cancel, onClick returns false and the checkbox is not checked.
onDblClick
Executes JavaScript code when a DblClick event occurs; that is, when the user double-clicks a form
element or a link.
Event handler for document, Link
Implemented in Navigator 4.0
Syntax
onDblClick="handlerText"
Parameters
Note
onDragDrop
Executes JavaScript code when a DragDrop event occurs; that is, when the user drops an object onto
the browser window, such as dropping a file.
Event handler for Window
Implemented in Navigator 4.0
Syntax
Page No:298
onDragDrop="handlerText"
Parameters
Security
Getting the data property of the DragDrop event requires the UniversalBrowserRead privilege. For
information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the JavaScript
Guide.
Description
The DragDrop event is fired whenever a system item (file, shortcut, and so on) is
dropped onto the browser window using the native system's drag and drop
mechanism. The normal response for the browser is to attempt to load the item
into the browser window. If the event handler for the DragDrop event returns
true, the browser loads the item normally. If the event handler returns false,
the drag and drop is canceled.
onError
Executes JavaScript code when an error event occurs; that is, when the loading of a document or
image causes an error.
Event handler for Image, Window
Implemented in Navigator 3.0
Syntax
onError="handlerText"
Parameters
Description
An error event occurs only when a JavaScript syntax or runtime error occurs, not when a browser
error occurs. For example, if you try set [Link]='[Link]' and
[Link] does not exist, the resulting error message is a browser error message; therefore,
onError would not intercept that message. However, an error event is triggered by a bad URL within
an IMG tag or by corrupted image data.
[Link] applies only to errors that occur in the window containing [Link], not in
other windows.
Page No:299
null to suppress all JavaScript error dialogs. Setting [Link] 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 returns false or does not return a value)
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)
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="[Link]" 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, including those for the Image object.
<SCRIPT>
[Link]=null
</SCRIPT>
<IMG NAME="imageBad1" SRC="[Link]" ALIGN="left" BORDER="2">
However, if the Image object has a custom onError event handler, the handler would execute if the
image had an error. This is because [Link]=null suppresses JavaScript error messages,
not onError event handlers.
<SCRIPT>
[Link]=null
function myErrorFunc() {
alert("The image had a nasty error.")
}
</SCRIPT>
<IMG NAME="imageBad1" SRC="[Link]" ALIGN="left" BORDER="2"
onError="myErrorFunc()">
In the following example, [Link]=null suppresses all error reporting. Without
onerror=null, the code would cause a stack overflow error because of infinite recursion.
<SCRIPT>
[Link] = 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>
[Link] = myOnError
Page No:300
msgArray = new Array()
urlArray = new Array()
lnoArray = new Array()
function myOnError(msg, url, lno) {
msgArray[[Link]] = msg
urlArray[[Link]] = url
lnoArray[[Link]] = lno
return true
}
function displayErrors() {
win2=[Link]('','window2','scrollbars=yes')
[Link]('<B>Error Report</B><P>')
for (var i=0; i < [Link]; i++) {
[Link]('<B>Error in file:</B> ' + urlArray[i] + '<BR>')
[Link]('<B>Line number:</B> ' + lnoArray[i] + '<BR>')
[Link]('<B>Message:</B> ' + msgArray[i] + '<P>')
}
[Link]()
}
</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: [Link]
Line number: 34
Message: unterminated string literal
Error in file: [Link]
Line number: 34
Message: missing ) after argument list
Error in file: [Link]
Line number: 30
Message: noSuchFunction is not defined
Example 4: Event handler calls a function. In the following IMG tag, onError calls the function
badImage if errors occur when the image loads.
<SCRIPT>
function badImage(theImage) {
alert('Error: ' + [Link] + ' did not load properly.')
}
</SCRIPT>
<FORM>
<IMG NAME="imageBad2" SRC="[Link]" ALIGN="left" BORDER="2"
onError="badImage(this)">
</FORM>
onFocus
Executes JavaScript code when a focus event occurs; that is, when a window, frame, or frameset
receives focus or when a form element receives input focus.
Event handler Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit,
for Text, Textarea, Window
Implemented in Navigator 2.0
Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame,
Password, Radio, Reset, Submit, and Window
Navigator 4.0: event handler of Layer
Syntax
onFocus="handlerText"
Parameters
Page No:301
handlerText JavaScript code or a call to a JavaScript function.
Description
The focus event can result from a focus method or from the user clicking the mouse on an object or
window or tabbing with the keyboard. Selecting within a field results in a select event, not a focus
event. onFocus executes JavaScript code when a focus event occurs.
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.
Note
In Navigator 3.0, on some platforms, placing an onFocus event handler in a FRAMESET tag has no
effect.
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()">
onKeyDown
Executes JavaScript code when a KeyDown event occurs; that is, when the user depresses a key.
Event handler for document, Image, Link, Textarea
Implemented in Navigator 4.0
Syntax
onKeyDown="handlerText"
Parameters
onKeyPress
Executes JavaScript code when a KeyPress event occurs; that is, when the user presses or holds down
a key.
Event handler for document, Image, Link, Textarea
Implemented in Navigator 4.0
Syntax
onKeyPress="handlerText"
Parameters
Description
onKeyUp
Executes JavaScript code when a KeyUp event occurs; that is, when the user releases a key.
Event handler for document, Image, Link, Textarea
Implemented in Navigator 4.0
Syntax
onKeyUp="handlerText"
Parameters
onLoad
Executes JavaScript code when a load event occurs; that is, when the browser finishes loading a
window or all frames within a FRAMESET tag.
Event handler for Image, Layer, Window
Implemented in Navigator 2.0
Navigator 3.0: event handler of Image
Syntax
onLoad="handlerText"
Parameters
Description
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).
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, onLoad 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 Image for information.
Examples
Page No:304
Example 1: Display message when page loads. In the following example, the onLoad event handler
displays a greeting message after a Web page is loaded.
<BODY onLoad="[Link]("Welcome to the Brave New World home page!")>
Example 2: 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)
[Link]=displayAlert
[Link]="[Link]"
function displayAlert(theImage) {
if (theImage==null) {
alert('An image loaded')
}
else alert([Link] + ' has been loaded.')
}
</SCRIPT>
<IMG NAME="imageB" SRC="[Link]" ALIGN="top"
onLoad=displayAlert(this)><BR>
Example 3: Looping GIF animation. The following example displays an image, [Link], 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="[Link]" BORDER=0
onLoad="++cycles">
<INPUT TYPE="button" VALUE="Count Loops"
onClick="alert('The animation has looped ' + cycles + ' times.')">
Example 4: 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, ![Link] is displayed. When that animation completes,
the onLoad event handler causes the next file, ![Link], to load in place of the first file. After the
last animation, ![Link], 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"
[Link]=imageName
} else {
whichImage=-1
return
}
}
</SCRIPT>
<IMG NAME="changingAnimation" SRC="![Link]" BORDER=0 ALIGN="top"
onLoad="changeAnimation(this)">
onMouseDown
Executes JavaScript code when a MouseDown event occurs; that is, when the user depresses a mouse
button.
Event handler for Button, document, Link
Implemented in Navigator 4.0
Page No:305
Syntax
onMouseDown="handlerText"
Parameters
Description
If onMouseDown returns false, the default action (entering drag mode, entering selection mode, or
arming a link) is canceled.
Arming is caused by a MouseDown over a link. When a link is armed it changes color to represent its
new state.
onMouseMove
Executes JavaScript code when a MouseMove event occurs; that is, when the user moves the cursor.
Event handler for None
Implemented in Navigator 4.0
Syntax
onMouseMove="handlerText"
Parameters
Event of
Because mouse movement happens so frequently, by default, onMouseMove is not an event of any
object. You must explicitly set it to be associated with a particular object.
Description
The MouseMove event is sent only when a capture of the event is requested by an object (see "Events
in Navigator 4.0").
Page No:306
onMouseOut
Executes JavaScript code when a MouseOut event occurs; that is, each time the mouse pointer leaves
an area (client-side image map) or link from inside that area or link.
Event handler for Layer, Link
Implemented in Navigator 3.0
Syntax
onMouseOut="handlerText"
Parameters
Description
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 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 onMouseOver.
Examples
onMouseOver
Executes JavaScript code when a MouseOver event occurs; that is, once each time the mouse pointer
moves over an object or area from outside that object or area.
Event handler for Layer, Link
Implemented in Navigator 2.0
Navigator 3.0: event handler of Area
Syntax
onMouseOver="handlerText"
Parameters
Description
Page No:307
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 onMouseOver 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 onMouseOver.
Examples
By default, the HREF value of an anchor displays in the status bar at the bottom of the browser when a
user places the mouse pointer over the anchor. In the following example, onMouseOver provides the
custom message "Click this if you dare."
<A HREF="[Link]
onMouseOver="[Link]='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.
onMouseUp
Executes JavaScript code when a MouseUp event occurs; that is, when the user releases a mouse
button.
Event handler for Button, document, Link
Implemented in Navigator 4.0
Syntax
onMouseUp="handlerText"
Parameters
Description
If onMouseUp returns false, the default action is canceled. For example, if onMouseUp returns false
over an armed link, the link is not triggered. Also, if MouseUp occurs over an unarmed link (possibly
due to onMouseDown returning false), the link is not triggered.
Page No:308
Note
Arming is caused by a MouseDown over a link. When a link is armed it changes color to represent its
new state.
onMove
Executes JavaScript code when a move event occurs; that is, when the user or script moves a window
or frame.
Event handler for Window
Implemented in Navigator 4.0
Syntax
onMove="handlerText"
Parameters
onReset
Executes JavaScript code when a reset event occurs; that is, when a user resets a form (clicks a Reset
button).
Event handler for Form
Implemented in Navigator 3.0
Syntax
onReset="handlerText"
Parameters
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>
onResize
Executes JavaScript code when a resize event occurs; that is, when a user or script resizes a window
or frame.
Event handler for Window
Implemented in Navigator 4.0
Syntax
onResize="handlerText"
Parameters
Description
This event is sent after HTML layout completes within the new window inner dimensions. This
allows positioned elements and named anchors to have their final sizes and locations queried, image
SRC properties can be restored dynamically, and so on.
onSelect
Executes JavaScript code when a select event occurs; that is, when a user selects some of the text
within a text or textarea field.
Event handler for Text, Textarea
Implemented in Navigator 2.0
Syntax
onSelect="handlerText"
Parameters
Examples
The following example uses onSelect in the valueField Text object to call the selectState
function.
<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">
onSubmit
Page No:310
Executes JavaScript code when a submit event occurs; that is, when a user submits a form.
Event handler for Form
Implemented in Navigator 2.0
Syntax
onSubmit="handlerText"
Parameters
Security
Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail
privilege. For information on security in Navigator 4.0, see Chapter 7, "JavaScript Security," in the
JavaScript Guide.
Description
You can use onSubmit 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.
Examples
In the following example, onSubmit calls the validate function to evaluate the data being
submitted. If the data is valid, the form is submitted; otherwise, the form is not submitted.
<FORM onSubmit="return validate(this)">
...
</FORM>
onUnload
Executes JavaScript code when an unload event occurs; that is, when the user exits a document.
Event handler for Window
Implemented in Navigator 2.0
Syntax
onUnload="handlerText"
Parameters
Description
Use onUnload 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).
Page No:311
Event properties used
Examples
In the following example, onUnload calls the cleanUp function to perform some shutdown
processing when the user exits a Web page:
<BODY onUnload="cleanUp()">
Page No:312