JAVASCR2
JAVASCR2
1
Table of Contents
JavaScript Working Document…4 Methods and Functions…74
The Mother of all Disclaimers …5 abs method…74
Learning JavaScript…5 acos method…75
JavaScript and Java…5 alert method…75
JavaScript Development…6 anchor method…76
Navigator Scripting…7 asin method…77
Using JavaScript in HTML …7 atan method…78
Scripting Event Handlers …9 back method…78
Tips and Techniques …12 big method…79
blink method…80
JavaScript Values, Names, and Literals…15
blur method…80
Values…15
bold method…81
Datatype Conversion…15
ceil method…82
Variable Names…16
charAt method…83
Literals…17
clear method…83
JavaScript Expressions and Operators…19
clearTimeout method…84
Expressions…19 click method…84
Conditional Expressions…19
close method (document object)…85
Assignment Operators (=, +=, -=, *=, /=)…20
close method (window object)…86
Operators…20 confirm method…87
Arithmetic Operators…20
cos method…87
Bitwise Operators…22
escape function…88
The JavaScript Object Model…26 eval function…89
Objects and Properties…26 exp method…89
Functions and Methods…27 fixed method…90
Creating New Objects…28 floor method…90
Using Built-in Objects and Functions…32 focus method…91
Using the String Object…32 fontcolor method…92
Using the Math Object…32 fontsize method…93
Using the Date Object…33 forward method…94
Using Built-in Functions…34 getDate method…94
Overview of JavaScript Statements…36 getDay method…95
Navigator Objects…37 getHours method…96
Using Navigator Objects…37 getMinutes method…96
Navigator Object Hierarchy…38 getMonth method…97
JavaScript and HTML Layout…39 getSeconds method…98
Key Navigator Objects…40 getTime method…98
Objects…42 getTimezoneOffset method…99
anchor object (client)…42 getYear method…99
button object (client)…43 go method…100
checkbox object (client)…44 indexOf method…101
Date object (common)…45 isNaN function…102
document object (client)…47 italics method…103
form object (client)…48 lastIndexOf method…103
frame object (client)…50 link method…104
hidden object (client)…52 log method…105
history object (client)…53 max method…106
link object (client)…54 min method…106
location object (client)…56 open method (document object)…107
Math object (common)…57 open method (window object)…108
navigator object (client)…59 parse method…110
password object (client)…59 parseFloat function…111
radio object (client)…61 parseInt function…112
reset object (client)…62 pow method…113
select object (client)…64 prompt method…113
string object (common)…66 random method…114
submit object (client)…67 round method…114
text object (client)…68 select method…115
textarea object (client)…70 setDate method…116
window object (client)…71 setHours method…116
2
setMinutes method…117 search property…162
setMonth method…117 selected property…164
setSeconds method…118 selectedIndex property…164
setTime method…118 self property…165
setTimeout method…119 SQRT1_2 property…166
setYear method…121 SQRT2 property…167
sin method…121 status property…167
small method…122 target property…168
sqrt method…123 text property…169
strike method…123 title property…169
sub method…124 top property…170
submit method…125 userAgent property…170
substring method…126 value property…171
sup method…126 vlinkColor property…172
tan method…127 window property…172
toGMTString method…128 Event handlers…174
toLocaleString method…128 onBlur event handler…174
toLowerCase method…129 onChange event handler…174
toString method…129 onClick event handler…175
toUpperCase method…130 onFocus event handler…176
unEscape function…131 onLoad event handler…176
UTC method…131 onMouseOver event handler…177
write method…132 onSelect event handler…177
writeln method…133 onSubmit event handler…178
Properties…135 onUnload event handler…178
action property…135 Statements…179
alinkColor property…136 break statement…179
anchors property…136 comment statement…179
appCodeName property…137 continue statement…180
appName property…138 for statement…180
appVersion property…138 for...in statement…181
bgColor property…139 function statement…182
checked property…140 if...else statement…182
cookie property…141 return statement…183
defaultChecked property…142 var statement…183
defaultSelected property…142 while statement…183
defaultStatus property…143 with statement…184
defaultValue property…144 Reserved words…185
E property…145 Color values…186
elements property…145 PERSISTENT CLIENT STATE…189
encoding property…146
HTTP COOKIES …189
fgColor property…147
INTRODUCTION …189
forms property…147
OVERVIEW …189
frames property…148
SPECIFICATION …189
hash property…149
Syntax of the Cookie HTTP Request Header…191
host property…149
EXAMPLES …192
hostname property…150
href property…151 JavaScript Snippets…194
index property…152 The Digital Clock…194
lastModified property…153
length property…153
linkColor property…154
links property…155
LN2 property…155
LN10 property…156
location property…156
method property…157
name property…158
options property…158
parent property…159
pathname property…159
PI property…160
port property…161
protocol property…161
referrer property…162
3
JavaScript Working Document
Current Version : Version 2, dated February 11, 1996
Next Update : March 3, 1996
Development of the JavaScript language and its documentation continues. Additional features are planned; some
current features could be modified if necessary.
Documentation Update
This document was prepared by Aj Brown of IPST from the original JavaScript Authoring Guide from
Netscape’s World Wide Web site : http://home.netscape.com
[email protected]
[email protected]
[email protected]
[email protected]
Compuserve : 102636,362
http://www.ipst.com
I encourage any and all comments, suggestions, or code snippets that we could include in this working document
to help fellow developers explore and take advantage of JavaScript.
If you have a code snippet you feel would be of value, please email it to me, and I will include it in the
next version.
Look for our HTML Primer and Reference in PDF format coming soon.
4
The Mother of all Disclaimers
JavaScript and its documentation are currently under development. Some of the language is not yet
implemented. That which is implemented is subject to change. Information provided at this time is incom-
plete and should not be considered a language specification. JavaScript is a work in progress whose
potential we'd like to share with you, the beta users, in this developmental form.
Learning JavaScript
JavaScript is a compact, object-based scripting language for developing client and server Internet applica-
tions. Netscape Navigator 2.0 interprets JavaScript statements embedded directly in an HTML page, and
LiveWire enables you to create server-based applications similar to common gateway interface (CGI)
programs.
In a client application for Navigator, JavaScript statements embedded in an HTML page can recognize
and respond to user events such as mouse clicks, form input, and page navigation.
For example, you can write a JavaScript function to verify that users enter valid information into a form
requesting a telephone number or zip code. Without any network transmission, an HTML page with
embedded JavaScript can interpret the entered text and alert the user with a message dialog if the input is
invalid. Or you can use JavaScript to perform an action (such as play an audio file, execute an applet, or
communicate with a plug-in) in response to the user opening or exiting a page.
JavaScript also supports functions, again without any special declarative requirements. Functions can be
properties of objects, executing as loosely typed methods.
JavaScript complements Java by exposing useful properties of Java applets to script authors. JavaScript
statements can get and set exposed properties to query the state or alter the performance of an applet or
plug-in.
Java is an extension language designed, in particular, for fast execution and type safety. Type safety is
reflected by being unable to cast a Java int into an object reference or to get at private memory by corrupt-
ing Java bytecodes.
Java programs consist exclusively of classes and their methods. Java's requirements for declaring classes,
writing methods, and ensuring type safety make programming more complex than JavaScript authoring.
Java's inheritance and strong typing also tend to require tightly coupled object hierarchies.
5
In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages like
HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience
because of their easier syntax, specialized built-in functionality, and minimal requirements for object
creation.
JavaScript Java
Compiled on server before execution on
Interpreted (not compiled) by client
client.
Object-based. Code uses built-in, extensible Object-orientated. Applets consist of object
objects, but no classes or inhereitance classes with inheritance.
Code integrated with, and embedded in, Applets distinct from HTML (accessed from
HTML. HTML pages)
Variable data types not declared (loose Variable data types must be declared (strong
typing). typing).
Dynamic binding; object references checked Static binding; object references must exist at
at run-time compile-time
Secure. cannot write to hard disk Secure. cannot write to hard disk
JavaScript Development
A script author is not required to extend, instantiate, or know about classes. Instead, the author acquires
finished components exposing high-level properties such as "visible" and "color", then gets and sets the
properties to cause desired effects.
As an example, suppose you want to design an HTML page that contains some catalog text, a picture of a
shirt available in several colors, a form for ordering the shirt, and a color selector tool that's visually
integrated with the form. You could write a Java applet that draws the whole page, but you'd face compli-
cated source encoding and forgo the simplicity of HTML page authoring.
A better route would use Java's strengths by implementing only the shirt viewer and color picker as
applets, and using HTML for the framework and order form. A script that runs when a color is picked
could set the shirt applet's color property to the picked color. With the availability of general-purpose
components like a color picker or image viewer, a page author would not be required to learn or write
Java. Components used by the script would be reusable by other scripts on pages throughout the catalog.
6
Navigator Scripting
• Using JavaScript in HTML
• Scripting Event Handlers
• Tips and Techniques
A script embedded in HTML with the SCRIPT tag uses the format:
<SCRIPT>
JavaScript statements...
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
JavaScript statements...
</SCRIPT>
The HMTL tag, <SCRIPT>, and its closing counterpart, </SCRIPT> can enclose any number of JavaScript
statements in a document.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
document.write("Hello net.")
</SCRIPT>
</HEAD>
<BODY>
That's all, folks.
</BODY>
</HTML>
7
Code Hiding
Scripts can be placed inside comment fields to ensure that your JavaScript code is not displayed by old browsers
that do not recognize JavaScript. The entire script is encased by HTML comment tags:
Scripts placed within SCRIPT tags are evaluated after the page loads. Functions are stored, but not executed.
Functions are executed by events in the page.
It's important to understand the difference between defining a function and calling the function. Defining the
function simply names the function and specifies what to do when the function is called. Calling the function
actually performs the specified actions with the indicated parameters.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- to hide script contents from old browsers
function square(i) {
document.write("The call passed ", i ," to the function.","<BR>")
return i * i
}
document.write("The function returned ",square(5),".")
// end hiding contents from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<BR>
All done.
</BODY>
</HTML>
Generally, you should define the functions for a page in the HEAD portion of a document. Since the HEAD is
loaded first, this practice guarantees that functions are loaded before the user has a chance to do anything that
might call a function.
8
Example 3: a script with two functions.
<HTML>
<HEAD>
<SCRIPT>
<!--- hide script from old browsers
function bar() {
document.write("<HR ALIGN='left' WIDTH=25%>")
}
function output(head, level, string) {
document.write("<H" + level + ">" + head + "</H" + level + "><P>" + string)
}
document.write(bar(),output("Make Me Big",3,"Make me ordinary."))
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<P>
Thanks.
</BODY>
</HTML>
Example 3 results.
Make Me Big
Make me ordinary.
Thanks.
Quotes
Use single quotes (') to delimit string literals so that scripts can distinguish the literal from attribute values enclosed
in double quotes. In the previous example, function bar contains the literal 'left' within a double-quoted attribute
value. Here's another example:
Event handlers are embedded in documents as attributes of HTML tags to which you assign JavaScript code to
execute. The general syntax is
9
where TAG is some HTML tag and eventHandler is the name of the event handler.
For example, suppose you have created a JavaScript function called compute. You can cause Navigator to
perform this function when the user clicks on a button by assigning the function call to the button's onClick event
handler:
You can put any JavaScript statements inside the quotes following onClick. These statements get executed when
the user clicks on the button. If you want to include more than one statement, separate statements with a semico-
lon (;).
In general, it is a good idea to define functions for your event handlers because:
• it makes your code modular-you can use the same function as an event handler for many different items.
• it makes your code easier to read.
Notice in this example the use of this.form to refer to the current form. The keyword this refers to the current
object-in the above example, the button object. The construct this.form then refers to the form containing the
button. In the above example, the onClick event handler is a call to the compute() function, with
this.form, the current form, as the parameter to the function.
If an event applies to an HTML tag, then you can define an event handler for it. In general, an event handler has
the name of the event, preceded by "on." For example, the event handler for the Focus event is onFocus.
Many objects also have methods that emulate events. For example, button has a click method that emulates the
button being clicked. Note: The event-emulation methods do not trigger event-handlers. So, for example, the
click method does not trigger an onClick event-handler. However, you can always call an event-handler directly
(for example, you can call onClick explicitly in a script).
10
Example 4: a script with a form and an event handler attribute.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function compute(form) {
if (confirm("Are you sure?"))
form.result.value = eval(form.expr.value)
else
alert("Please come back again.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
<BR>
</FORM>
</BODY>
</HTML>
Enter an expression: 9 + 5
Result: 14
Example 5: a script with a form and event handler attribute within a BODY tag.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function checkNum(str, min, max) {
if (str == "") {
alert("Enter a number in the field, please.")
return false
}
for (var i = 0; i < str.length; i++) {
var ch = str.substring(i, i + 1)
if (ch < "0" || ch > "9") {
alert("Try a number, please.")
return false
}
}
var num = 0 + str
if (num < min || num > max) {
alert("Try a number from 1 to 10.")
return false
}
return true
11
}
function thanks() {
alert("Thanks for your input.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Please enter a small number:
<INPUT NAME="num"
ONCHANGE="if (!checkNum(this.value, 1, 10))
{this.focus();this.select();} else {thanks()}"
VALUE="0">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
document.write("<PRE>")
document.writeln("Field name: " + document.forms[0].num.name)
document.writeln("Field value: " + document.forms[0].num.value)
document.write("</PRE>")
</SCRIPT>
</BODY>
</HTML>
Updating Pages
JavaScript in Navigator generates its results from the top of the page down. Once something has been formatted,
you can't change it without reloading the page. Currently, you cannot update a particular part of a page without
updating the entire page. However, you can update a "sub-window" in a frame separately.
Printing
You cannot currently print output created with JavaScript. For example, if you had the following in a page:
And you printed it, you would get only "This is some text", even though you would see both lines on-screen.
Using Quotes
Be sure to alternate double quotes with single quotes. Since event handlers in HTML must be enclosed in quotes,
12
you must use single quotes to delimit arguments.
For example
<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
onClick="window.open('stmtsov.html', 'newWin', 'toolbar=no,directories=no')">
</FORM>
Defining Functions
It is always a good idea to define all of your functions in the HEAD of your HTML page. This way, all functions
will be defined before any content is displayed. Otherwise, the user might perform some action while the page is
still loading that triggers an event handler and calls an undefined function, leading to an error.
Creating Arrays
An array is an ordered set of values that you reference through an array name and an index. For example, you
could have an array called emp, that contains employees' names indexed by their employee number. So emp[1]
would be employee number one, emp[2] employee number two, and so on.
JavaScript does not have an explicit array data type, but because of the intimate relationship between arrays and
object properties (see JavaScript Object Model), it is easy to create arrays in JavaScript. You can define an
array object type, as follows:
function MakeArray(n) {
this.length = n;
for (var i = 1; i <= n; i++) {
this[i] = 0 }
return this
}
}
This defines an array such that the first property, length, (with index of zero), represents the number of elements in
the array. The remaining properties have an integer index of one or greater, and are initialized to zero.
You can then create an array by a call to new with the array name, specifying the number of elements it has. For
example:
This creates an array called emp with 20 elements, and initializes the elements to zero.
Populating an Array
You can populate an array by simply assigning values to its elements. For example:
and so on.
13
You can also create arrays of objects. For example, suppose you define an object type named Employees, as
follows:
Then you can easily display the objects in this array using the show_props function (defined in the section on the
JavaScript Object Model) as follows:
14
JavaScript Values, Names, and Literals
• Values
• Variable Names
• Literals
Values
JavaScript recognizes the following types of values:
This relatively small set of types of values, or data types, enables you to perform useful functions with
your applications.Notice that there is no explicit distinction between integer and real-valued numbers. Nor
is there an explicit date data type. However, the date object and related built-in functions enable you to
handle dates.
Objects and functions are the other fundamental elements in the language. You can think of objects as
named containers for values, and functions as procedures that your application can perform.
Datatype Conversion
JavaScript is a loosely typed language. That means that you do not have to specify the datatype of a
variable when you declare it, and datatypes are converted automatically as needed during the course of
script execution.
JavaScript will attempt to convert an expression to the datatype of the left-hand operand. Expressions are
always evaluated from left to right, so JavaScript applies this rule at each step in the evaluation of a
complex expression.
var anumber = 42
x = astring + anumber
y = anumber + astring
15
The first statement will convert anumber to a string value, because the left-hand operand, astring, is a
string. The statement will then concatenate the two strings, so x will have a value of "742".
Conversely, the second statement will convert astring to a numeric value, because the left-hand operand,
anumber, is a number. The statement then adds the two numbers, so y will have a value of 49.
JavaScript cannot convert some strings to numbers. For example, the statements
var anumber = 42
y = anumber + astring
NOTE: Much of the functionality specified in this table is not implemented as of Navigator beta4.
Variable Names
You use variables to hold values in your application. You give these variables names by which you
reference them, and there are certain rules to which the names must conform.
A JavaScript identifier or name must start with a letter or underscore ("_"); subsequent characters can also
16
be digits (0-9). Letters include the characters "A" through "Z" (uppercase) and the characters "a" through
"z" (lowercase). JavaScript is case-sensitive.
Some examples of legal names are:
• Number_hits
• temp99
• _name
Literals
Literals are the way you represent values in JavaScript. These are fixed values that you literally provide in
your application source, and are not variables. Examples of literals include:
• 42
• 3.14159
• "To be or not to be"
Integers
Integers can be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8) format. A decimal
integer literal consists of a sequence of digits (optionally suffixed as described below) without a leading 0
(zero).
An integer can be expressed in octal or hexadecimal rather than decimal. A leading 0 (zero) on an integer
literal means it is in octal; a leading 0x (or 0X) means hexadecimal. Hexadecimal integers can include
digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7.
A floating point literal can have the following parts: a decimal integer, a decimal point ("."), a fraction
(another decimal number), an exponent, and a type suffix. The exponent part is an "e" or "E" followed by
an integer, which can be signed (preceded by a "+" or "-"). A floating point literal must have at least one
digit, plus either a decimal point or "e" (or "E"). Some examples of floating point literals are:
• 3.1415 • -3.1E12
• .1e12 • 2E-12
Boolean Literals
The boolean type has two literal values: true and false.
String Literals
A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be
delimited by quotes of the same type; that is, either both single quotes or double quotes. The following are
examples of string literals:
17
• "blah" • 'blah'
• "1234" • "one line \n another line"
Special Characters
You can use the following special characters in JavaScript string literals:
• \b indicates a backspace.
• \f indicates a a form feed.
• \n indicates a new line character.
• \r indicates a carriage return.
• \t indicates a tab character.
18
JavaScript Expressions and Operators
• Expressions
• Operators
• Arithmetic Operators
• Bitwise Operators
• Logical Operators
• Comparison Operators
• String Operators
• Operator Precedence
Expressions
An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single
value. The value may be a number, a string, or a logical value. Conceptually, there are two types of
expressions: those that assign a value to a variable, and those that simply have a value. For example, the
expression
x = 7
is an expression that assigns x the value 7. This expression itself evaluates to 7. Such expressions use
assignment operators. On the other hand, the expression
3 + 4
simply evaluates to 7; it does not perform an assignment. The operators used in such expressions are
referred to simply as operators.
The special keyword null denotes a null value. In contrast, variables that have not been assigned a value
are undefined, and cannot be used without a run-time error.
Conditional Expressions
A conditional expression can have one of two values based on a condition. The syntax is
If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You can use a
conditional expression anywhere you would use a standard expression.
For example,
The other operators are shorthand for standard arithmetic operations as follows:
• x += y means x = x + y
• x -= y means x = x - y
• x *= y means x = x * y
• x /= y means x = x / y
• x %= y means x = x % y
Operators
LiveScript has arithmetic, string, and logical operators. There are both binary and unary operators. A
binary operator requires two operands, one before the operator and one after the operator:
For example, 3 + 4 or x * y
A unary operator requires a single operand, either before or after the operator:
operator operand
or
operand operator
Arithmetic Operators
Arithmetic operators take numerical values (either literals or variables) as their operands and return a
20
single numerical value.
Standard Arithmetic Operators
The standard arthmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).
These operators work in the standard way.
Modulus (%)
The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in
the statement above, where var1 and var2 are variables. The modulo function is the remainder of inte-
grally dividing var1 by var2. For
example, 12 % 5 returns 2.
Increment (++)
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.
y = x++
y = ++x
Decrement (--)
var-- or --var
This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for ex-
ample x--) then it returns the value before decrementing. If used prefix (for example, --x), then it returns
the value after decrementing.
21
decrements x to 2 and sets y to 3.
If x is 3, then the statement
y = --x
The unary negation operator must precede its operand. It negates its operand. For example,
x = -x
Bitwise Operators
Bitwise operators treat their operands as a set of bits (zeros and ones), rather than as decimal, hexadeci-
mal, or octal numbers. For example, the decimal number 9 has a binary representation of 101. Bitwise
operators perform their operations on such binary representations, but they return standard JavaScript
numerical values.
• The operands are converted to 32-bit integers, and expressed a series of bits (zeros and ones).
• Each bit in the first operand is paired with the corresponding bit in the second operand: first bit
to first bit, second bit to second bit, and so on.
• The operator is applied to each pair of bits, and the result is constructed bitwise.
The 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
22
controlled by the operator used.
Shift operators convert their operands to 32-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.
Example TBD.
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.
Example TBD.
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the
right are discarded.
Zero bits are shifted in from the left.
Example TBD.
Logical Operators
Logical operators take logical (Boolean) values as operands. They return a logical value. Logical values
are true and false.
And (&&)
The logical "and" operator returns true if both logical expressions expr1 and expr2 are true. Otherwise, it
returns false.
Or (||)
The logical "or" operator returns true if either logical expression expr1 or expr2 is true. If both expr1 and
expr2 are false, then it returns false.
Not (!)
23
Usage: !expr
The logical "not" operator is a unary operator that negates its operand expression expr. That is, if expr is
true, it returns false, and if expr is false, then it returns true.
Short-Circuit Evaluation
As logical expressions are evaluated left to right, they are tested for possible "short circuit" evaluation
using the following rule:
The rules of logic guarantee that these evaluations will always be correct. Note that the anything part of
the above expressions is not evaluated, so any side effects of doing so do not take effect.
A comparison operator compares its operands and returns a logical value based on whether the compari-
son is true or not. The operands may be numerical or string values. When used on string values, the
comparisons are based on the standard lexicographical ordering.
String Operators
In addition to the comparison operators, which may be used on string values, the concatenation operator
(+) concatenates two string values together, returning another string that is the union of the two operand
strings. For example,
"my string"
The shorthand assignment operator += can also be used to concatenate strings. For example, if the vari-
able mystring is a string that has the value "alpha", then the expression
mystring += "bet"
24
evaluates to "alphabet" and assigns this value to mystring.
Operator Precedence
The precedence of operators determines the order they are applied when evaluating an expression. You
can override operator precedence by using parentheses.
comma ,
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
conditional ?:
logical-or ||
logical-and &&
bitwise-or |
bitwise-xor ^
bitwise-and &
equality == !=
relational < <= > >=
shift << >> >>>
addition/subtraction + -
multiply/divide * / %
negation/increment ! ~ - ++ --
call, member () [] .
25
The JavaScript Object Model
JavaScript is based on a simple object-oriented paradigm. An object is a construct with properties that are
JavaScript variables. Properties can be other objects. Functions associated with an object are known as the
object's methods.
In addition to objects that are built into the Navigator client and the LiveWire server, you can define your
own objects.
objectName.propertyName
Both the object name and property name are case sensitive.
You define a property by assigning it a value. For example, suppose there is an object named myCar (we'll discuss
how to create objects later-for now, just assume the object already exists). You can give it properties named
make, model, and year as follows:
myCar.make = "Ford"
myCar.model = "Mustang"
myCar.year = 69;
An array is an ordered set of values associated with a single variable name. Properties and arrays in
JavaScript are intimately related; in fact, they are different interfaces to the same data structure. So, for
example, you could access the properties of the myCar object described above as follows:
myCar["make"] = "Ford"
myCar["model"] = "Mustang"
myCar["year"] = 67;
myCar[0] = "Ford"
myCar[1] = "Mustang"
myCar[2] = 67;
This type of an array is known as an associative array, because each index element is also associated with a string
value. To illustrate how this works, the following function displays the properties of the object, when you pass the
object and the object's name as arguments to the function:
26
function show_props(obj, obj_name) {
So, the function call show_props(myCar, "car") would return the following:
myCar.make = Ford
myCar.model = Mustang
myCar.year = 67
The statements in a function can include other function calls defined for the current application. A function can be
recursive, that is, it can call itself.
function pretty_print(string) {
document.write("<HR><P>" + string)
This function takes a string as its argument, adds some HTML tags to it using the concatenation operator (+),
then displays the result to the current document.
Defining a function does not execute it. You have to call the function for it to do its work. For example,
you could call the pretty_print function as follows:
<SCRIPT>
</SCRIPT>
27
The parameters of a function are not limited to just strings and numbers. You can pass whole objects to a func-
tion, too.
Methods
A method is a function associated with an object. You define a method in the same way as you define a
standard function. Then, use the following syntax to associate the function with an existing object:
object.methodname = function_name
where object is an existing object, methodname is the name you are assigning to the method, and
function_name is the name of the function.
You can then call the method in the context of the object as follows:
object.methodname(params);
JavaScript has a special keyword, this, that you can use to refer to the current object. For example, sup-
pose you have a function called validate that validates an object's value property, given the object, and the
high and low values:
alert("Invalid Value!")
Then, you could call validate in each form element's onChange event handler, using this to pass it the
form element, as in the following example:
To define an object type, create a function for the object type that specifies its name, and its properties and
28
methods. For example, suppose you want to create an object type for cars. You want this type of object to be
called car, and you want it to have properties for make, model, year, and color. To do this, you would write the
following function:
this.make = make;
this.model = model;
this.year = year;
}
Notice the use of this to assign values to the object's properties based on the values passed to the function.
This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make
is the string "Eagle", car1.year is the integer 1993, and so on.
You can create any number of car objects by calls to new. For example,
An object can have a property that is itself another object. For example, suppose I define an object called
person as follows:
this.name = name;
this.age = age;
this.sex = sex;
}
Then we can rewrite the definition of car to include an owner property that takes a person object, as
follows:
this.make = make;
this.model = model;
29
this.year = year;
this.owner = owner;
}
car2.owner.name
Note that you can always add a property to a previously defined object. For example, the statement:
car1.color = "black"
adds a property color to car1, and assigns it a value of "black". However, this does not affect any other
objects. To add the new property to all objects of the same type, you have to add the property to the
definition of the car object type.
Defining Methods
You can define methods for an object type by including a method defnition in the object type definition.
For example, suppose you have a set of image GIF files, and you want to define a method that displays
the information for the cars, along with the corresponding image. You could define a function such as:
function displayCar() {
var result = "A Beautiful " + this.year
+ " " + this.make + " " + this.model;
pretty_print(result)
}
where pretty_print is the previously defined function to display a string. Notice the use of this to refer to
the object to which the method belongs.
You can make this function a method of car by adding the statement
this.displayCar = displayCar;
to the object definition. So, the full definition of car would now look like:
30
Then you can call this new method as follows:
car1.displayCar()
car2.displayCar()
31
Using Built-in Objects and Functions
The JavaScript Language contains the following built-in objects and functions:
• String object
• Math object
• Date object
• Built-in functions
These objects and their properties and methods are built into the language. You can use these objects in
both client applications with Netscape Navigator and server applications with LiveWire.
creates a string object called mystring. The literal "blah" is also a string object.
For example, given the above object, mystring.toUpperCase() returns "HELLO, WORLD!", and so
does "hello, world!".toUpperCase().
Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarith-
mic, exponential, and
other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56)
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) {
32
a = PI * r*r;
y = r*sin(theta)
x = r*cos(theta)
JavaScript handles dates very similarly to Java. The two languages have many of the same date methods,
and both languages store dates as the number of milliseconds since January 1, 1970 00:00:00.
where varName is a JavaScript variable name for the date object being created; it can be a new object or a
property of an existing object.
The parameters for the Date constructor can be any of the following:
• Nothing: creates today's date and time. For example, today = new Date()
• A string representing a date in the following form: "Month day, year hours:minutes:seconds".
For example, Xmas95= new Date("December 25, 1995 13:30:00") If you omit hours,
minutes, or seconds, the value will be set to zero.
• A set of integer values for year, month, and day. For example, Xmas95 = new Date(95,11,25)
• A set of values for year, month, day, hour, minute, and seconds For example, Xmas95 = new
Date(95,11,25,9,30,0)
The Date object has a large number of methods for handling dates and times. The methods fall into these
broad categories:
• "set" methods, for setting date and time values in date objects
• "get" methods, for getting date and time values from date objects
• "to" methods, for returning string values from date objects.
• parse and UTC methods, for parsing date strings.
The "get" and "set" methods enable you to get and set seconds, minutes, hours, day of the month, day of
the week, months, and years separately. There is a getDay method that returns the day of the week, but no
corresponding setDay method, because the day of the week is set automatically. These methods use
integers to represent these values as follows:
• seconds and minutes: 0 to 59
33
• hours: 0 to 23
• day: 0 to 6 (day of the week)
• date: 1 to 31 (day of the month)
• months: 0 (January) to 11 (December)
• year: years since 1900
The getTime and setTime methods are useful for comparing dates. The getTime method returns the
number of milliseconds since the epoch for a date object.
For example, the following code displays the number of shopping days left until Christmas:
nextXmas.setYear(today.getYear())
daysLeft = Math.round(daysLeft);
This example creates a date object named today that contains today's date. It then creates a date object
named nextXmas, and sets the year to the current year. Then, using the number of milliseconds per day, it
computes the number of days between today and nextXmas, using getTime, and rounding to a whole
number of days.
The parse method is useful for assigning values from date strings to existing date objects. For example,
the following code uses parse and setTime to assign a date to the IPOdate object.
IPOdate.setTime(Date.parse("Aug 9, 1995"))
34
The eval Function
The built-in function eval takes a string or numeric expression as its arguement. If the arguement is a string, it
attempts to convert it to a numeric expression, evaluates the expression, and returns the value. If the arguement is
an expression, it evaluates the expression.
This function is useful for evaluating a string representing a numerical expression to a number. For example, input
from a form element is always in a string, but you often want to convert it to a numerical value.
The following example takes input in a text field, applies the eval function and displays the result in another text
field. If you type a numerical expression in the first field, and click on the button, the expression will be evaluted.
For example, enter "(666 * 777) / 3", and click on the button to see the result.
<SCRIPT>
function compute(obj) {
obj.result.value = eval(obj.expr.value)
</SCRIPT>
<FORM NAME="evalform">
<BR>
<BR>
</FORM>
TBD
35
Overview of JavaScript Statements
JavaScript supports a compact set of statements that nevertheless enables you to incorporate a great deal
of interactivity in web pages.
Further overview information TBD. Refer to statements reference for specific information.
36
Navigator Objects
• Using Navigator Objects
• Navigator Object Hierarchy
• JavaScript and HTML Layout
• Key Navigator Objects
• window: the top-level object; contains properties that apply to the entire window. There is also a
window object for each "child window" in a frames document.
• location: contains properties on the current URL
• history: contains properties representing URLs the user has previously visited
• document: contains properties for content in the current document, such as title, background color,
and forms
The properties of the document object are largely content-dependent. That is, they are created based on
the content that you put in the document. For example, the document object has a property for each form
and each anchor in the document.
For example, suppose you create a page named simple.html that contains the following HTML:
As always, there would be window, location, history, and document objects. These would have properties
such as:
• location.href = "http://www.terrapin.com/samples/vsimple.html"
• document.title = "A Simple Document"
• document.fgColor = #000000
• document.bgColor = #ffffff
• history.length = 7
37
These are just some example values. In practice, these values would be based on the document's actual
location, its title, foreground and background colors, and so on.
Navigator would also create the following objects based on the contents of the page:
• document.myform
• document.myform.Check1
• document.myform.Button1
• document.myform.action = http://terrapin/mocha/formproc()
• document.myform.method = get
• document.myform.length = 5
• document.myform.Button1.value = Press Me
• document.myform.Button1.name = Button1
• document.myform.text1.value = blahblah
• document.myform.text1.name = text1
• document.myform.Check1.defaultChecked = true
• document.myform.Check1.value = on
• document.myform.Check1.name = Check1
Notice that each of the property references above starts with "document," followed by the name of the
form, "myform," and then the property name (for form properties) or the name of the form element. This
sequence follows the Navigator's object hierarchy, discussed in the next section.
In this hierarchy, an object's "descendants" are properties of the object. For example, a form named
"form1" is an object, but is also a property of document, and is referred to as "document.form1". The
Navigator object hierarchy is illustrated below:
navigator
window
|
+--parent, frames, self, top
|
+--location
|
+--history
|
+--document
|
+--forms
| |
| elements (text fields, textarea, checkbox, password
| radio, select, button, submit, reset)
38
+--links
|
+--anchors
To refer to specific properties of these objects, you must specify the object name and all its ancestors.
Exception: You are not required to include the window object.
Because of this "top-down" behavior, JavaScript only reflects HTML that it has encountered. For ex-
ample, suppose you define a form with a couple of text input elments:
<FORM NAME="statform">
<input type = "text" name = "username" size = 20>
<input type = "text" name = "userage" size = 3>
Then these form elements are reflected as JavaScript objects document.statform.username and
document.statform.userage, that you can use anywhere after the form is defined. However, you could not
use these objects before the form is defined. So, for example, you could display the value of these objects
in a script after the form definition:
<SCRIPT>
document.write(document.statform.username.value)
document.write(document.statform.userage.value)
</SCRIPT>
However, if you tried to do this before the form definition (i.e. above it in the HTML page), you would
get an error, since the objects don't exist yet in the Navigator.
Likewise, once layout has occurred, setting a property value does not affect its value or its appearance.
For example, suppose you have a document title defined as follows:
This is reflected in JavaScript as the value of document.title. Once the Navigator has displayed this in
layout (in this case, in the title bar of the Navigator window), you cannot change the value in JavaScript.
So, if later in the page, you have the following script:
it will not change the value of document.title nor affect the appearance of the page, nor will it generate an
error.
39
Key Navigator Objects
Some of the most useful Navigator objects include document, form, and window.
One of the most useful Navigator objects is the document object, because its write and writeln methods can
generate HTML. These methods are the way that you display JavaScript expressions to the user. The only
difference between write and writeln is that writeln adds a carriage return at the end of the line. However, since
HTML ignores carriage returns, this will only affect preformatted text, such as that inside a PRE tag.
The document object also has onLoad and onUnload event-handlers to perform functions when a user first
loads a page and when a user exits a page.
There is only one document object for a page, and it is the ancestor for all the form, link, and anchor
objects in the page.
Navigator creates a form object for each form in a document. You can name a form with the NAME
attribute, as in this example:
<FORM NAME="myform">
<INPUT TYPE="text" NAME="quantity" onChange="...">
...
</FORM>
There would be a JavaScript object named myform based on this form. The form would have a property
corresponding to the text object, that you would refer to as
document.myform.quantity
document.myform.quantity.value
The forms in a document are stored in an array called forms. The first (topmost in the page) form is
forms[0], the second forms[1], and so on. So the above references could also be:
document.forms[0].quantity
document.forms[0].quantity.value
Likewise, the elements in a form, such as text fields, radio buttons, and so on, are stored in an elements
array.
The window object is the "parent" object for all other objects in Navigator. You can always omit the
object name in references to window properties and methods.
40
Window has several very useful methods that create new windows and pop-up dialog boxes:
The window object has properties for all the frames in a frameset. The frames are stored in the frames
array. The frames array contains an entry for each child frame in a window. For example, if a window
contains three child frames, these frames are reflected as window.frames[0], window.frames[1], and
window.frames[2].
The status property enables you to set the message in the status bar at the bottom of the client window.
41
Objects
The following objects are available in JavaScript:
• anchor • Math
• button • navigator
• checkbox • password
• Date • radio
• document • reset
• form • select
• frame • string
• hidden • submit
• history • text
• link • textarea
• location • window
NOTE: Each object topic indicates whether the object is part of the client (in Navigator), server (in
LiveWire), or is common (built-in to JavaScript). Server objects are not included in this version of the
documentation.
Syntax
<A NAME="anchorName">
[HREF=locationOrURL]
anchorText
</A>
NAME=”anchorname” specifies a tag that becomes an available hypertext target within the current document.
HREF=locationorURL identifies a destination anchor or URL.
anchorText specifies the text to display at the anchor.
xxx to be supplied
Description
You can reference the anchor objects in your code by using the anchors property of the document object.
The anchors property is an array that contains an entry for each anchor in a document.
Properties
none
42
Methods
none
Event handlers
None.
Examples
See also
• link object
• anchors property
Syntax
To define a button:
<INPUT
TYPE="button"
NAME="buttonName"
VALUE="buttonText"
[onClick="handlerText"]>
NAME=”buttonName” specifies the name of the button object as a property of the enclosing form object and
can be accessed using the name property.
VALUE=”buttonText” specifies the label to display on the button face and can be accessed using the value
property.
1. buttonName.propertyName
2. buttonName.methodName(parameters)
3. formname.elements.[index].propertyName
4. formname.elements.[index].methodname(parameters)
43
Description
A button object is a form element and must be defined with a <FORM>...</FORM> tag.
The button object is a custom button that you can use to perform an action you define.
Properties
• name
• value
Methods
• click
Event handlers
• onClick
Examples
A custom button does not necessarily load a new page into the client; it merely executes the script speci-
fied by the onClick event handler. In the following example, myfunction() is a JavaScript function.
See also
Syntax
To define a checkbox, use standard HTML syntax with the addition of the onClick event handler:
<INPUT
TYPE="checkbox"
NAME="checkboxName"
[CHECKED]
[onClick="handlerText"]>
textToDisplay
1. checkboxName.propertyName
2. checkboxName.methodName(parameters)
44
checkboxName is the value of the NAME attribute of a checkbox object.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.
Description
A checkbox object is a form element and must be defined within a <FORM>...</FORM> tag.
Use the checked property to specify whether the checkbox is currently checked. Use the defaultChecked prop-
erty to specify whether the checkbox is checked when the form is loaded.
Properties
Methods
• click
Event handlers
• onClick
Examples
See also
Syntax
dateObjectName.methodName(parameters)
Exceptions: The Date object's parse and UTC methods are static methods that you use as follows:
Date.UTC(parameters)
Date.parse(parameters)
Description
Form 1 of the syntax creates today's date and time. If you omit hours, minutes, or seconds from form 2 or
4 of the syntax, the value will be set to zero.
JavaScript handles dates 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.
JavaScript does not have a date data type, but you can use the Date object and its methods to work with
dates and times in your applications. The Date object has many methods for setting, getting, and manipu-
lating dates.
Properties
None.
Methods
• getDate • setDate
• getDay • setHours
• getHours • setMinutes
• getMinutes • setMonth
• getMonth • setSeconds
• getSeconds • setTime
• getTime • setYear
• getTimeZoneoffset • toGMTString
• getYear • toLocaleString
• parse • UTC
46
Event handlers
Examples
Syntax
To define a document object, use standard HTML syntax with the addition of the onLoad and onUnLoad
event handlers:
<BODY
BACKGROUND="backgroundImage"
BGCOLOR="#backgroundColor"
FGCOLOR="#foregroundColor"
LINK="#unfollowedLinkColor"
ALINK="#activatedLinkColor"
VLINK="#followedLinkColor"
[onLoad="handlerText"]
[onUnLoad="handlerText"]>
</BODY>
BGCOLOR, FGCOLOR, LINK, ALINK, and VLINK are color specifications expressed as a hexadecimal
RGB triplet (in
the format "#rrggbb") or as one of the string literals listed in the Color Appendix.
1. document.propertyName
2. document.methodName(parameters)
Description
The <BODY>...</BODY> tag encloses an entire document, which is defined by the current URL. The
47
entire body of the document (all other HTML elements for the document) goes within the <BODY>...</BODY>
tag.
You can reference the anchors, forms, and links of a document by using the anchors, forms, and links
properties. These properties are arrays that contain an entry for each anchor, form, or link in a document.
Properties
Methods
• clear
• close
• open
• write
• writeln
Event handlers
None. The onLoad and onUnload event handlers are specified in the <BODY> tag but are actually event han-
dlers for the window object.
Examples
xxx to be supplied
See also
• frame and window objects
48
Syntax
To define a form, use standard HTML syntax with the addition of the onSubmit event handler:
<FORM
NAME=”formName”
TARGET="windowName"
ACTION="serverURL"
METHOD=GET | POST
ENCTYPE=”encodingType”
[onSubmit="handlerText"]>
</FORM>
TARGET specifies the window that form responses go to. When you submit a form with a TARGET attribute,
server responses are displayed in the specified window instead of the window that contains the form.
windowName may be an existing window created by previous targetted form submits or link clicks; it may also
refer to named frames in a <FRAMESET> tag; it may also be _top, _parent, _self, or _blank.
ACTION secifies the URL of the server to which form field input information is sent. “GET” is the default value.
METHOD GET | POST specifies how information is sent to the server specified by ACTION. GET (the default)
appends the input information to the URL which on most receiving systems becomes the value of the environment
variable QUERY_STRING. POST sends the input information in a data body which is available on stdin with the
data length set in the environment variable CONTENT_LENGTH.
1. formName.propertyName
2. formName.methodName(parameters)
3. forms[index].propertyName
4. forms[index].methodName(parameters)
Description
You can reference the form objects in your code by using the forms property of the document object. The
forms property is an array that contains an entry for each form in a document.
You can reference a form's elements in your code by using the form name or the forms property of the document
object. The forms property is an array that contains an entry for each form in a document.
49
Properties
Methods
• submit
Event handlers
• onSubmit
Examples
xxx to be supplied
See also
• elements and forms properties
Syntax
To define a frame object, use standard HTML syntax. The onLoad and onUnload event handlers are specified in
the <FRAMESET> tag but are actually event handlers for the window object :
<FRAMESET
ROWS="rowHeightValueList"
COLS="columnWidthList">
textToDisplay
[onLoad=”handlerText”]
[onUnload=”handlerText”]
[<FRAME SRC="locationOrURL" NAME="frameName">]
</FRAMESET>
ROWS =”rowHeightValueList” is a comma-separated list of values specifying the row-height of the frame. An
optional suffix defines the units. Default units are pixels.
COLS=”columnWidthList” is a comma-separated list of values specifying the column-width of the frame. An
optional suffix defines the units. Default units are pixels.
textToDisplay specifies the text to display in the frame.
FRAME defines a frame.
SRC=”locationOrURL” specifies the URL of the document to be displayed in the frame.
50
NAME=”frameName” specifies a name to be used as a target of hypertext links.
frameName is the value of the NAME attribute in the <FRAME> tag of a frame object.
propertyName is one of the properties listed below.
methodName is one of the methods listed below.
index is an integer representing a frame object.
Description
The <FRAMESET> tag is used in an HTML document whose sole purpose is to define the layout of the sub-
HTML documents, or frames, that make up the page. Each frame is a window object.
You can reference the frame objects in your code by using the frames property of the window object. The frames
property is an array that contains an entry for each frame in a window containing a <FRAMESET> tag.
If a <FRAME> tag contains SRC and NAME attributes, you can refer to that frame from a sibling frame by using
parent.frameName or parent.frames[index]. For example, if the fourth frame in a set has
NAME="homeFrame", sibling frames can refer to that frame using parent.homeFrame or
parent.frames[3].
Properties
A frame object is a type of window and has the same properties as a window object. Some properties, however,
have no effect on a frame because frames do not have all the features of windows; for example, setting status and
defaultStatus has no effect because a frame has no status bar.
• defaultStatus
• frames
• parent
• self
• status
• top
• window
Methods
A frame object is a type of window and has the same methods as a window object.
• alert
• close
• confirm
• open
• prompt
• setTimeout
• clearTimeout
51
Event handlers
None. The onLoad and onUnload event handlers are specified in the <FRAMESET> tag but are actually event
handlers for the window object.
Examples
xxx to be supplied
See also
Syntax
<INPUT
TYPE="hidden"
NAME="hiddenName"
[VALUE="textValue"]
NAME="hiddenName" specifies the name of the hidden object as a property of the enclosing form object and
can be accessed using the name property.
VALUE="textValue" specifies the value of the hidden object and can be accessed using the value property.
1. hiddenName.propertyName
2. formName.elements[index].propertyName
Description
A hidden object is a form element and must be defined within a <FORM>...</FORM> tag.
You can use hidden objects instead of cookies for client/server communication.
Properties
• defaultValue
52
• name reflects the NAME argument
• value reflects the VALUE argument
Methods
None.
Event handlers
None.
Examples
xxx to be supplied
See also
• cookie property
Syntax
1. history.propertyName
2. history.methodName(parameters)
Description
The history object is a linked list of URLs the user has visited, as shown in the Navigator's Go menu.
Properties
• length
Methods
• back
• forward
• go
53
Event handlers
None.
Examples
The following example goes to the URL the user visited three clicks ago.
history.go(-3)
See also
• location object
Syntax
To define a link, use standard HTML syntax with the addition of the onClick and onMouseOver event
handlers:
<A [NAME="anchorName"]
HREF=locationOrURL
TARGET="windowName"
[onClick="handlerText"]
[onMouseOver="handlerText"]>
linkText
</A>
NAME=”anchorName” specifies a tag that becomes an available hypertext target within the current document.
HREF=locationOrURL identifies a destination anchor or URL.
TARGET=”windowName” specifies the window that the link is loaded into. WindowName can be an existing
window created by previous targeted form submits or link clicks; it can be a frame name specified in a
<FRAMESET> tag; or it can be one of the magic frame names _top, _parent, _self, or _blank.
linkText is rendered as a hypertext link to the URL.
document.links[index].propertyName
54
Description
You can reference the link objects in your code by using the links property of the document object. The links
property is an array that contains an entry for each link in a document.
When you specify a URL, you can use JavaScript statements in addition to using standard URL formats. The
following list shows the syntax for specifying some of the most common types of URLs.
Properties
Methods
None.
Event handlers
• onClick
• onMouseOver
Examples
The following example takes the user back x entries in the history list:
55
See also
• anchor object
• links property
Syntax
1. location.propertyName
2. location.methodName(parameters)
Description
The location object represents a complete URL. Each property of the location object represents a different
portion of the URL.
The following diagram of a URL shows the relationships between the location properties:
protocol represents the beginning of the URL, up to and including the first colon.
hostname represents the domain name or IP address of a network host.
port represents the port number to connect to.
pathname represents the url-path portion of the URL.
search represents any query information in the URL, beginning with a question mark.
hash represents an anchor name fragment in the URL, beginning with a hash mark (#).
The location object has two other properties not shown in the diagram above:
The location object is contained by the window object and is within its scope. If you reference a location object
without specifying a window, the location object represents the current location. If you reference a location object
and specify a window name, for example, windowName.location.propertyName , the location object repre-
sents the location of the specified window.
Do not confuse the location object with the location property of the document object. You cannot change the
value of the location object, but you can change the value of the location property. Also, the location object has
56
properties, and the location property does not. document.location is a string-valued property that usually
matches what window.location is set to when you load the document, but redirection may change it.
Properties
• hash
• host
• hostname
• href
• pathname
• port
• protocol
• search
Methods
• assign
• toString
Event handlers
None.
Examples
xxx to be supplied
See also
• history object
• location property
Syntax
57
Description
You reference the constant PI as Math.PI. Constants are defined with the full precision of real numbers in
JavaScript.
Similarly, you reference Math functions as methods. For example, the sine function is
Math.sin(argument)
, where argument is the argument.
It is often convenient to use the with statement when a section of code uses several Math constants and methods,
so you don't have to type "Math" repeatedly. For example,
with (Math) {
a = PI * r*r
y = r*sin(theta)
x = r*cos(theta)
}
Properties
• E
• LN10
• LN2
• PI
• SQRT1_2
• SQRT2
Methods
• abs • max
• acos • min
• asin • pow
• atan • random
• ceil • round
• cos • sin
• exp • sqrt
• floor • tan
Event handlers
Examples
xxx to be supplied
58
navigator object (client)
The navigator object contains information about the version of Navigator in use.
Syntax
navigator.<I>propertyName</I>
Description
Use the navigator object to determine which version of the Navigator your users have.
Properties
• appName
• appVersion
• appCodeName
• userAgent
Methods
None.
Event handlers
None.
Examples
See also
• link object
• anchors property
59
Syntax
<INPUT
TYPE="password"
NAME="passwordName"
[VALUE="textValue"]
SIZE=integer>
NAME="passwordName" specifies the name of the password object as a property of the enclosing form object
and can be accessed using the name property.
VALUE="textValue" specifies the value of the password object and can be accessed using the value property.
SIZE=integer specifies the number of characters in the password object.
1. passwordName.propertyName
2. passwordName.methodName(parameters)
3. formName.elements[index].propertyName
4. formName.elements[index].methodName(parameters)
Description
A password object is a form element and must be defined within a <FORM>...</FORM> tag.
Properties
• defaultValue
• name reflects the NAME argument
• value reflects the VALUE argument
Methods
• focus
• blur
• select
Event handlers
None.
60
Examples
See also
Syntax
To define a set of radio buttons, use standard HTML syntax with the addition of the onClick event han-
dler:
<INPUT
TYPE="radio"
NAME="radioName"
VALUE="buttonValue"
[CHECKED]
[onClick="handlerText"]>
textToDisplay
NAME="radioName" specifies the name of the radio object as a property of the enclosing form object and can
be accessed using the name property. All radio buttons in a group should have the same NAME attribute.
VALUE="buttonValue" specifies the value returned when the radio button is selected and can be accessed
using the value property. This defaults to "on".
CHECKED specifies that the radio button is selected and can be accessed using the checked property.
textToDisplay specifies the label to display beside the radio button and can be accessed using the value property
1. radioName[index1].propertyName
2. radioName[index1].methodName(parameters)
3. formName.elements[index2].propertyName
4. formName.elements[index2].methodName(parameters)
61
Description
A radio object is a form element and must be defined within a <FORM>...</FORM> tag.
All radio buttons in a radio button group use the same name property. To access the individual radio buttons in
your code, follow the object name with an index starting from zero, one for each button the same way you would
for an array such as forms: document.forms[0].radioName[0] is the first,
document.forms[0].radioName[1] is the second, etc.
Properties
• checked reflects the CHECKED argument
• defaultChecked
• index
• length
• name reflects the NAME argument
• value reflects the VALUE argument
Methods
• click
Event handlers
• onClick
Examples
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. JavaScript automatically sets the catalog name input
field based on the radio buttons.
See also
62
Syntax
To define a reset button, use standard HTML syntax with the addition of the onClick event handler:
<INPUT
TYPE="reset"
NAME="resetName"
VALUE="buttonText"
[onClick="handlerText"]>
NAME="resetName" specifies the name of the reset object as a property of the enclosing form object and can
be accessed using the name property.
VALUE="buttonText" specifies the text to display on the button face and can be accessed using the value
property.
1. resetName.propertyName
2. resetName.methodName(parameters)
3. formName.elements[index].propertyName
4. formName.elements[index].methodName(parameters)
Description
A reset object is a form element and must be defined within a <FORM>...</FORM> tag.
Properties
Methods
• click
Event handlers
• onClick
Examples
The following example displays a text object containing "CA". If the user types a different state abbreviation in the
text object and then clicks the Clear Form button, the original value of "CA" is restored.
63
<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2">
<P><INPUT TYPE="reset" VALUE="Clear Form">
See also
Syntax
To define a select object, use standard HTML syntax with the addition of the onBlur, onChange, and
onFocus event handlers:
<SELECT
NAME="selectName"
[SIZE="integer"]
[MULTIPLE]
[onBlur="handlerText"]
[onChange="handlerText"]
[onFocus="handlerText"]>
<OPTION [SELECTED]> textToDisplay [ ... <OPTION> textToDisplay]
</SELECT>
NAME="selectName" specifies the name of the select object as a property of the enclosing form object and
can be accessed using the name property.
SIZE="integer" specifies the number of options visible when the form is displayed and can be accessed using
the length property.
MULTIPLE specifies that the select object is a scrolling list (not a selection list).
OPTION specifies a selection element in the list.
SELECTED specifies that the option is selected by default and can be accessed using the selected property.
textToDisplay specifies the text to display in the list and can be accessed using the value property.
1. selectName.propertyName
2. selectName.methodName(parameters)
3. formName.elements[index].propertyName
4. formName.elements[index].methodName(parameters)
Description
A select object is a form element and must be defined within a <FORM>...</FORM> tag.
You can reference the options of a select object in your code by using the options property. The options property
is an array that contains an entry for each option in a select object: selectName.options[0] is the first,
selectName.options[1] is the second, etc. Each option has the properties listed below.
Properties
Methods
None.
Event handlers
• onBlur
• onChange
• onFocus
Examples
65
<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>
See also
Syntax
1. stringName.propertyName
2. stringName.methodName(parameters)
Description
A string can be represented as a literal enclosed by single or double quotes; for example, "Netscape" or
'Netscape'.
Properties
• length
Methods
Event handlers
last_name.length is 8.
last_name.toUpperCase() is "SCHAEFER".
last_name.toLowerCase() is "schaefer".
See also
Syntax
To define a submit button, use standard HTML syntax with the addition of the onClick event handler:
<INPUT
TYPE="submit"
NAME="submitName"
VALUE="buttonText"
[onClick="handlerText"]>
NAME="submitName" specifies the name of the submit object as a property of the enclosing form object and
can be accessed using the name property.
VALUE="buttonText" specifies the label to display on the button face and can be accessed using the value
property.
1. submitName.propertyName
2. submitName.methodName(parameters)
3. formName.elements[index].propertyName
4. formName.elements[index].methodName(parameters)
Description
A submit object is a form element and must be defined within a <FORM>...</FORM> tag.
67
Clicking a submit button submits a form to the program 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.
Properties
Methods
• click
Event handlers
• onClick
Examples
See also
Syntax
To define a text object, use standard HTML syntax with the addition of the onBlur, on Change, onFocus,
and onSelect event handlers:
<INPUT
TYPE="text"
NAME="textName"
VALUE="textValue"
SIZE=integer
[onBlur="handlerText"]
[onChange="handlerText"]
[onFocus="handlerText"]
[onSelect="handlerText"]>
NAME="textName" specifies the name of the text object as a property of the enclosing form object and can be
accessed using the name property.
68
VALUE="textValue" specifies the value of the text object and can be accessed using the value property.
SIZE=integer specifies the number of characters in the text object.
Description
A text object is a form element and must be defined within a <FORM>...</FORM> tag.
text objects can be updated (redrawn) dynamically by setting the value property (this.value).
Properties
• defaultValue
• name reflects the NAME argument
• value reflects the VALUE argument
Methods
• focus
• blur
• select
Event handlers
• onBlur
• onChange
• onFocus
• onSelect
Examples
See also
69
textarea object (client)
A textarea object is a multiline input field on an HTML form. A textarea field lets the user enter words, phrases,
or numbers.
Syntax
To define a text area, use standard HTML syntax with the addition of the onBlur, onChange, onFocus, and
onSelect event handlers:
<TEXTAREA
NAME="textareaName"
ROWS="integer"
COLS="integer"
[onBlur="handlerText"]
[onChange="handlerText"]
[onFocus="handlerText"]
[onSelect="handlerText"]>
textToDisplay
</TEXTAREA>
NAME="textareaName" specifies the name of the textarea object as a property of the enclosing form object
and can be accessed using the name property.
ROWS="integer" and COLS="integer" define the physical size of the displayed input field in numbers of
characters.
textToDisplay specifies the value of the textarea object and can be accessed using the value property. A textarea
allows only ASCII text, and new lines are respected.
1. textareaName.propertyName
2. textareaName.methodName(parameters)
3. formName.elements[index].propertyName
4. formName.elements[index].methodName(parameters)
Description
A textarea object is a form element and must be defined within a <FORM>...</FORM> tag.
textarea objects can be updated (redrawn) dynamically by setting the value property (this.value).
Properties
• defaultValue
• name reflects the NAME argument
• value reflects the VALUE argument
70
Methods
• focus
• blur
• select
Event handlers
• onBlur
• onChange
• onFocus
• onSelect
Examples
<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.
Syntax
windowVar is the name of a new window. Use this variable when referring to a window's properties, methods,
and containership.
windowName is the window name to use in the TARGET argument of a <FORM> or <A> tag.
xxx and location object? For details on defining a window, see the open method.
To define an onLoad or onUnload event handler for a window object, use the <BODY> or <FRAMESET> tags:
<BODY
...
[onLoad="<I>handlerText</I>"]
[onUnload="<I>handlerText</I>"]>
</BODY>
<FRAMESET
ROWS="<I>rowHeightValueList</I>"
COLS="<I>columnWidthList</I>"
[onLoad="<I>handlerText</I>"]
[onUnload="<I>handlerText</I>"]>
[<FRAME SRC="locationOrURL" NAME="frameName">]
</FRAMESET>
</PRE>
For information on the <BODY> and <FRAMESET> tags, see the document and frame objects.
Description
The window object is the top-level object in the JavaScript client hierarchy. The top window is a "document
window" or "Web Browser window". Frame objects are also windows.
Because the existence of the current window is assumed, you do not have to reference the name of the window
when you call its methods and assign its properties. For example, status="Jump to a new location" is a
valid property assignment, and close() is a valid method call.
The self and window properties are synonyms for the current window, and you can optionally use them to refer to
the current window. For example, you can close the current window by calling either window.close() or
self.close(). You can use these properties to make your code more readable, or to disambiguate the prop-
erty reference self.status from a form called status. See the properties and methods listed below for more
examples.
You can reference a window's frame objects in your code by using the frames property. The frames property is
an array that contains an entry for each frame in a window containing a <FRAMESET> tag.
Windows lack event handlers until some HTML is loaded into them containing a <BODY> or <FRAMESET>
tag.
Properties
• defaultStatus
• frames
• parent
• self
72
• status
• top
• window
Methods
• alert
• close
• confirm
• open
• prompt
• setTimeout
• clearTimeout
Event handlers
• onLoad
• onUnload
Examples
xxx to be supplied
See also
73
Methods and Functions
The following methods and functions are available in JavaScript:
• abs • close • getSeconds • parseInt • sqrt
• acos • confirm • getTime • pow • strike
• alert • cos • getTimeZoneoffset • prompt • sub
• anchor • escape • getYear • random • submit
• asin • eval • go • round • substring
• atan • exp • indexOf • select • sup
• back • fixed • italics • setDate • tan
• big • floor • lastIndexOf • setHours • toGMTString
• blink • focus • link • setMinutes • toLocaleString
• blur • fontcolor • log • setMonth • toLowerCase
• bold • fontsize • max • setSeconds • toString
• ceil • forward • min • setTimeout • toUpperCase
• charAt • getDate • open (document) • setTime • unEscape
• clear • getDay • open (window) • setYear • UTC
• clearTimeout • getHours • parse • sin • write
• click • getMinutes • parseFloat • small • writeln
• close (document) • getMonth • isNaN
abs method
Returns the absolute value of its argument.
Syntax
Math.abs(number)
Applies to
Math
Examples
In the following example, the user enters a number in the first text box and presses the Calculate button to
display the absolute value of the number.
<FORM>
<P>Enter a number:
<INPUT TYPE="text" NAME="absEntry">
<P>The absolute value is:
<INPUT TYPE="text" NAME="result">
<P>
<INPUT TYPE="button" VALUE="Calculate" onClick="form.result.value =
Math.abs(form.absEntry.value)">
</FORM>
74
acos method
Returns the arc cosine (in radians) of its argument.
Syntax
Math.acos(number)
number should be a numeric expression between -1 and 1. The acos method returns a numeric value
between 0 and pi radians. If the value of number is outside the suggested range, the return value is always
0.
Applies to
Math
Examples
See also
alert method
Displays an Alert dialog box with a message and an OK button.
Syntax
alert("message")
Description
Use the alert method to display a message that does not require a user decision. The message argument specifies
a message that the dialog box contains.
Applies to
• window
75
Examples
In the following example, the testValue function checks the name entered by a user in the text element 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 of an application to enter a valid value.
function testValue(textElement) {
if (textElement.length > 8) {
alert("Please enter a name that is 8 characters or less")
}
}
You can call the testValue function in the onBlur event handler of a form's text element, as shown in the
following example:
See also
anchor method
Creates an HTML anchor that is used as a hypertext target.
Syntax
text.anchor(nameAttribute)
Description
Use the anchor method with the write or writeln methods to programatically create and display an anchor in a
document. Create the anchor with the anchor method, then call write or writeln to display the anchor in a docu-
ment.
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 HTML <A> tag.
Applies to
string
Examples
The following example opens the msgWindow window and creates an anchor for the Table of Contents:
76
var myString="Table of Contents"
msgWindow=window.open("","displayWindow")
msgWindow.document.writeln(myString.anchor("contents_anchor"))
msgWindow.document.close()
The previous example produces the same output as the following HTML:
See also
• link method
asin method
Returns the arc sine (in radians) of its argument.
Syntax
Math.asin(number)
number should be a numeric expression between -1 and 1. The asin method returns a numeric value
between -pi/2 and pi/2 radians. If the value of number is outside the suggested range, the return value is
always 0.
Applies to
Math
Examples
See also
77
atan method
Returns the arc tangent (in radians) of its argument.
Syntax
Math.atan(number)
number is a numeric expression representing the tangent of an angle. The atan method returns a numeric value
between -pi/2 and pi/2 radians.
Applies to
Math
Examples
See also
back method
Loads the previous URL in the history list.
Syntax
history.back()
Description
This method performs the same action as a user choosing the Back button in the Navigator. The back
method is the same as history.go(-1).
Applies to
history
Examples
78
The following custom buttons perform the same operations as the Navigator Back and Forward buttons:
• forward, go methods
big method
Causes the calling string object to be displayed in a big font by surrounding it with the HTML font tags
<BIG> and </BIG>.
Syntax
stringName.big()
Description
Use the big method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
The following example uses string methods to change the size of a string:
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:
<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>
See also
79
blink method
Causes the calling string object to blink by surrounding it with the HTML tags <BLINK> and </BLINK>.
Syntax
stringName.blink()
Description
Use the blink method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
The following example uses string methods to change the formatting of a string:
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>
See also
blur method
Removes focus from the specified object.
Syntax
1. passwordName.blur()
2. textName.blur()
3. textareaName.blur()
80
passwordName is either the value of the NAME attribute of a password object or an element in the elements
array.
textName is either the value of the NAME attribute of a text object or an element in the elements array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.
Description
Use the blur method to remove focus from a specific form element.
Applies to
Examples
The following example removes focus from the password element userPass:
userPass.blur()
See also
bold method
Causes the calling string object to be displayed as bold by surrounding it with the HTML tags <B> and
</B>.
Syntax
stringName.bold()
Description
Use the bold method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
81
The following example uses string methods to change the formatting of a string:
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>
See also
ceil method
Returns the least integer greater than or equal to its argument.
Syntax
Math.ceil(number)
Applies to
Math
Examples
See also
• floor method
82
charAt method
Returns the character at the specified index.
Syntax
stringName.charAt(index)
stringName is any string or a property of an existing object.
index is any integer from 0 to stringName.length() - 1.
Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last
character is stringName.length - 1.
Applies to
string
Examples
The following example displays characters at different locations in the string "Brave new world".
See also
clear method
Clears the window.
Syntax
document.clear()
Description
The clear method empties the content of a window, regardless of how the content of the window has been
painted.
83
Applies to
document
Examples
When the following function is called, the clear method empties the contents of the msgWindow window:
function windowCleaner() {
msgWindow.document.clear()
msgWindow.document.close()
}
See also
clearTimeout method
Cancels a timeout that was set with the setTimeout method.
Syntax
clearTimeout(timeoutID)
timeoutID is a timeout setting that was returned by a previous call to the setTimeout method.
Description
Applies to
window
Examples
See also
• setTimeout method
click method
Simulates a mouse click on the calling form element.
Syntax
84
1. buttonName.click()
2. radioName.click()
3. checkboxName.click()
buttonName is either the value of the NAME attribute of a button, reset, or submit object or an element in the
elements array.
radioName is an element in a radio array.
checkboxName is either the value of the NAME attribute of a checkbox object or an element in the elements
array.
Description
The effect of the click method varies according to the calling element:
• For button, reset, and submit, performs the same action as clicking the button.
• For a radio, selects a radio button.
• For a checkbox, checks the check box and sets its value to on.
Applies to
Examples
The following example toggles the selection status of the first element in the musicType radio group on
the musicForm form:
document.musicForm.musicType[0].click()
The following example toggles the selection status of the newAge checkbox on the musicForm form:
document.musicForm.newAge.click()
Syntax
document.close()
Description
The close method closes a stream opened with the document.open() method. If the stream was opened to layout,
the close method forces the content of the stream to display. Font style tags, such as <BIG> and <CENTER>,
automatically close a layout stream without calling the close method.
The close method also stops the "meteor shower" in the Netscape icon and displays "Document: Done" in
85
the status bar.
Applies to
document
Examples
The following function calls document.close() to close a stream that was opened with document.open().
The document.close() method forces the content of the stream to display in the window.
function windowWriter1() {
var myString = "Hello, world!"
msgWindow.document.open()
msgWindow.document.write("<P>" + myString)
msgWindow.document.close()
}
See also
Syntax
window.close()
Description
Applies to
window
Examples
window.close()
self.close()
close()
See also
• open method
86
confirm method
Displays a Confirm dialog box with the specified message and OK and Cancel buttons.
Syntax
confirm("message")
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.
Applies to
window
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 applica-
tion.
function confirmCleanUp() {
if (confirm("Are you sure you want to quit this application?")) {
cleanUp()
}
}
You can call the confirmCleanUp function in the onClick event handler of a form's pushbutton, as shown
in the following example:
See also
cos method
Returns the cosine of its argument.
Syntax
87
Math.cos(number)
number is a numeric expression representing the size of an angle in radians. The cos method returns a numeric
value between -1 and 1, which represents the cosine of the angle.
Applies to
Math
Examples
See also
escape function
Returns the ASCII encoding of an argument in the ISO Latin-1 character set.
Syntax
escape(char)
Description
The escape function is a built-in JavaScript function. It is not a method associated with any object, but is part of
the language itself.
The value returned by the escape function is a string of the form "%xx", where xx is the ASCII encoding of the
argument.
Examples
See also
• unEscape function
eval function
The eval function takes a JavaScript arithmetic expression as its argument and returns the value of the argument as
a number.
Syntax
eval(expression)
Description
The eval function is a built-in JavaScript function. It is not a method associated with any object, but is part of the
language itself.
Example
In the following example, both uses of eval assign the value 42 to the variable result.
x = 6
result = eval((3+3)*7)
result = eval(x*7)
exp method
Returns e to the power of its argument, i.e. ex, where x is the argument, and e is Euler's constant, the base of the
natural logarithms.
Syntax
Math.exp(number)
Applies to
Math
89
Examples
See also
fixed method
Causes the calling string object to be displayed in fixed-pitch font by surrounding it with the HTML tags
<TT> and </TT>.
Syntax
stringName.fixed()
Description
Use the fixed method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
The following example uses the fixed method to change the formatting of a string:
document.write(worldString.fixed())
The previous example produces the same output as the following HTML:
<TT>Hello, world</TT>
floor method
Returns the greatest integer less than or equal to its argument.
Syntax
Math.floor(number)
90
number is any numeric expression.
Applies to
Math
Examples
See also
• ceil method
focus method
Gives focus to the specified object.
Syntax
1. passwordName.focus()
2. textName.focus()
3. textareaName.focus()
passwordName is either the value of the NAME attribute of a password object or an element in the elements
array.
textName is either the value of the NAME attribute of a text object or an element in the elements array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.
Description
Use the focus method to navigate to a specific form element and give it focus. You can then either programatically
enter a value in the element or let the user enter a value.
Applies to
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 field and the select method highlights it so
91
the user can re-enter the password.
function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
userPass.focus()
userPass.select()
}
}
See also
fontcolor method
Causes the calling string object to be displayed in the specified color by surrounding it with the HTML tags
<FONT COLOR=color> and </FONT>.
Syntax
stringName.fontcolor(color)
Description
Use the fontcolor method with the write or writeln methods to format and display a string in a document.
If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the
hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is
"FA8072".
Applies to
string
Examples
The following example uses the fontcolor method to change the color of a string
92
document.write(worldString.fontcolor("maroon") + " is maroon in this line")
document.write("<P>" + worldString.fontcolor("salmon") + " is salmon in this
line")
document.write("<P>" + worldString.fontcolor("red") + " is red in this line")
The previous example produces the same output as the following HTML:
fontsize method
Causes the calling string object to be displayed in the specified font size by surrounding it with the HTML font
size tags <FONTSIZE=size> ... </FONTSIZE>.
Syntax
stringName.fontsize(size)
Description
Use the fontsize method with the write or writeln methods to format and display a string in a document. When you
specify size as an integer, you set the size of stringName to one of the seven defined sizes. When you specify
size as a string such as "-2", you adjust the font size of stringName relative to the size set in the BASEFONT
tag.
Applies to
string
Examples
The following example uses string methods to change the size of a string:
93
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:
<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>
See also
forward method
Loads the next URL in the history list.
Syntax
history.forward()
Description
This method performs the same action as a user choosing the Forward button in the Navigator. The for-
ward method is the same as history.go(1).
Applies to
history
Examples
The following custom buttons perform the same operations as the Navigator Back and Forward buttons:
See also
• back, go methods
getDate method
Returns the day of the month for a date object.
Syntax
dateObjectName.getDate()
94
dateObjectName is either the name of a date object or a property of an existing object.
Description
Applies to
Date
Examples
The second statement below assigns the value 25 to the variable day, based on the value of the date object
Xmas95.
• setDate method
getDay method
Returns the day of the week for a date object.
Syntax
dateObjectName.getDay()
Description
The value returned by getDay is an integer corresponding to the day of the week: zero for Sunday, one for
Monday, two for Tuesday, and so on.
Applies to
Date
Examples
The second statement below assigns the value 1 to weekday, based on the value of the date object
Xmas95. This is because December 25, 1995 is a Monday.
95
getHours method
Returns the hour for a date object.
Syntax
dateObjectName.getHours()
Description
Applies to
Date
Examples
The second statement below assigns the value 23 to the variable hours, based on the value of the date object
Xmas95.
See also
• setHours method
getMinutes method
Returns the minutes in a date object.
Syntax
dateObjectName.getMinutes()
Description
Applies to
Date
96
Examples
The second statement below assigns the value 15 to the variable minutes, based on the value of the date
object Xmas95.
See also
• setMinutes method
getMonth method
Returns the month in a date object.
Syntax
dateObjectName.getMonth()
Description
The value returned by getMonth is an integer between zero and eleven. Zero corresponds to January, one to
February, and so on.
Applies to
Date
Examples
The second statement below assigns the value 11 to the variable month, based on the value of the date
object Xmas95.
See also
• setMonth method
97
getSeconds method
Returns the seconds in the current time.
Syntax
dateObjectName.getSeconds()
Description
Applies to
Date
Examples
The second statement below assigns the value 30 to the variable secs, based on the value of the date object
Xmas95.
See also
• setSeconds method
getTime method
Returns the numeric value corresponding to the time for a date object.
Syntax
dateObjectName.getTime()
Description
The value returned by the getTime method is the number of milliseconds since the epoch (1 January 1970
00:00:00). You can use this method to help assign a date and time to another date object.
Applies to
98
Date
Examples
See also
• setTime method
getTimezoneOffset method
Returns the time zone offset in minutes for the current locale.
Syntax
dateObjectName.getTimezoneOffset()
Description
The time zone offset is the difference between local time and GMT. This value would be a constant except for
daylight savings time.
Applies to
Date
Examples
x = new Date()
currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60
getYear method
Returns the year in the date object.
Syntax
dateObjectName.getYear()
The value returned by getYear is the year less 1900. For example, if the year is 1976, the value returned is 76.
Applies to
Date
Examples
The second statement below assigns the value 95 to the variable year, based on the value of the date
object Xmas95.
See also
• setYear method
go method
Loads a URL in the history list.
Syntax
history.go(delta | "location")
Description
The go method navigates to the location in the history list determined by the argument that you specify.
The delta argument is a positive or negative integer. If delta is greater than zero, the go method loads the
URL that is that number of entries forward in the history list; otherwise, it loads the URL that is that
number of entries backward in the history list.
The location argument is a string. Use location to load the nearest history entry whose URL contains
location as a substring. The location to URL matching is case-insensitive
Applies to
history
Examples
100
The following button navigates to the nearest history entry that contains the string "home.netscape.com":
The following button navigates to the URL that is three entries backward in the history list:
See also
indexOf method
Returns the index within the calling string object of the first occurrence of the specified value, starting the search at
fromIndex.
Syntax
stringName.indexOf(character, [fromIndex])
Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of
the last character is stringName.length - 1.
Applies to
string
Examples
The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world".
See also
isNaN function
On Unix platforms, evaluates an argument to determine if it is "NaN".
Syntax
isNaN(testValue)
Description
The isNaN function is a built-in JavaScript function. It is not a method associated with any object, but is part of
the language itself. isNaN is available on Unix platforms only.
On all platforms except Windows, the parseFloat and parseInt functions return "NaN" when they evaluate a value
that is not a number. The "NaN" value is not a number in any radix. You can call the isNaN function to determine
if the result of parseFloat or parseInt is "NaN". If "NaN" is passed on to arithmetic operations, the operation
results will also be "NaN".
Examples
The following example evaluates floatValue to determine if it is a number, then calls a procedure accordingly.
floatValue=parseFloat(toFloat)
if isNaN(floatValue) {
notFloat()
} else {
isFloat()
}
See also
• parseFloat and parseInt functions
102
italics method
Causes the calling string object to be italicized by surrounding it with the HTML tags <I> and </I>.
Syntax
stringName.italics()
Description
Use the italics method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
The following example uses string methods to change the formatting of a string:
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>
See also
lastIndexOf method
Returns the index within the calling string object of the last occurrence of the specified value. The calling string is
searched backwards, starting at fromIndex.
Syntax
stringName.lastIndexOf(searchValue, [fromIndex])
103
stringName is any string or a property of an existing object.
searchValue is a string representing the value to search for.
fromIndex is the location within the calling string to start the search from, any integer from 0 to
stringName.length() - 1.
Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last
character is stringName.length - 1.
If you do not specify a value for fromIndex, JavaScript assumes stringName.length() - 1 (the end of the
string) by default.
Applies to
string
Examples
The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world".
//Displays 8
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
//Displays 10
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
//Displays 6
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new"))
See also
link method
Creates an HTML hypertext link that jumps to another URL.
Syntax
linkName.link(hrefAttribute)
Use the link method with the write or writeln methods to programatically create and display a hypertext
link in a document. Create the link with the link method, then call write or writeln to display the link in a docu-
ment.
In the syntax, the linkName string represents the literal text that you want the user to see. The
hrefAttribute string represents the HREF attribute of the HTML A tag, and it should be a valid URL.
Applies to
string
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="http://www.netscape.com"
document.open()
document.write("Click to return to " + hotText.link(URL))
document.close()
The previous example produces the same output as the following HTML:
See also
• anchor method
log method
Returns the natural logarithm (base e) of its argument.
Syntax
Math.log(number)
number is any positive numeric expression. If the value of number is outside the suggested range, the return value
is always -1.797693134862316e+308.
Applies to
Math
Examples
105
//Displays the value 2.302585092994046
document.write("The natural log of 10 is " + Math.log(10))
See also
• exp, pow methods
max method
Returns the greater of its two arguments.
Syntax
max(number1, number2)
Applies to
Math
Examples
See also
• min method
min method
Returns the lesser of its two arguments.
Syntax
min(number1, number2)
Math
Examples
See also
• max method
Syntax
document.open(["mimeType"])
text/html
text/plain
image/gif
image/jpeg
image/xbm
plugIn
Description
The open method opens a stream to collect the output of write or writeln methods. If the mimeType is text or
image, the stream is opened to layout; otherwise, the stream is opened to a plug-in. If a document exists in the
target window, the open method clears it.
End the stream by using the document.close() method. The close method causes text or images that were sent to
layout to display. After using document.close(), issue document.open() again when you want to begin another
output stream.
mimeType is an optional argument that specifies the type of document to which you are writing. If you do not
107
specify a mimeType, the open method assumes text/html by default.
Applies to
document
Examples
The following function calls document.open() to open a stream before issuing a write method:
function windowWriter1() {
var myString = "Hello, world!"
msgWindow.document.open()
msgWindow.document.write("<P>" + myString)
msgWindow.document.close()
}
See also
Syntax
toolbar[=yes|no]|[=1|0]
location[=yes|no]|[=1|0]
directories[=yes|no]|[=1|0]
status[=yes|no]|[=1|0]
menubar[=yes|no]|[=1|0]
scrollbars[=yes|no]|[=1|0]
108
resizable[=yes|no]|[=1|0]
width=pixels
height=pixels
You may use any subset of these options. Separate options with a comma. Do not put spaces between the
options.
Description
The open method opens a new web browser window on the client, similar to choosing File|New Web
Browser from the menu of the Navigator. The URL argument specifies the URL contained by the new
window. If URL is an empty string, a new, empty window is created.
In event handlers, you must specify window.open() instead of simply using open(). Due to the scoping of
static objects in JavaScript, a call to open() without specifying an object name is equivalent to
document.open().
windowFeatures is an optional, comma-separated list of options for the new window. The boolean
windowFeatures options are set to true if they are specified without values, or as yes or 1. For example,
open("", "messageWindow", "toolbar") and open("", "messageWindow", "toolbar=1") both set
the toolbar option to true. If windowName does not specify an existing window and you do not specify
windowFeatures, all boolean windowFeatures are true by default.
Applies to
window
Examples
In the following example, the windowOpener function opens a window and uses write methods to display
a message:
function windowOpener() {
109
msgWindow=window.open("","Display
window","toolbar=no,directories=no,menubar=no")
msgWindow.document.write("<HEAD><TITLE>Message window</TITLE></HEAD>")
msgWindow.document.write("<CENTER><BIG><B>Hello, world!</B></BIG></CENTER>")
}
The following is an onClick event handler that opens a new client window displaying the content speci
fied in the file sesame.html. It opens it with the specified option settings and names the corre
sponding window object newWin.
<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
onClick="window.open('sesame.html', 'newWin',
'toolbar=no,directories=no,menubar=no,status=yes,width=300,height=300')">
</form>
Notice the use of single quotes (') inside the onClick event handler.
See also
• close method
parse method
Returns the number of milliseconds in a date string since January 1, 1970 00:00:00, local time.
Syntax
Date.parse(dateString)
Description
The parse method takes a date string (such as "Dec 25, 1995"), and returns the number of milliseconds
since January 1, 1970 00:00:00 (local time). This function is useful for setting date values based on string
values, for example in conjunction with the setTime method and the Date object.
Given a string representing a time, parse returns the time value. It accepts the IETF standard date syntax: "Mon,
25 Dec 1995 13:30:00 GMT". It understands the continental US time zone abbreviations, but for general use, use
a time zone offset, for example "Mon, 25 Dec 1995 13:30:00 GMT+0430" (4 hours, 30 minutes west of the
Greenwich meridian). If you do not specify a time zone, the local time zone is assumed. GMT and UTC are
considered equivalent.
Because the parse function is a static method of Date, you always use it as Date.parse(), rather than as a
method of a date object you created.
Applies to
110
Date
Examples
IPOdate.setTime(Date.parse("Aug 9, 1995"))
See also
• UTC method
parseFloat function
Parses a string argument and returns a floating point number.
Syntax
parseFloat(string)
Description
The parseFloat function is a built-in JavaScript function. It is not a method associated with any object, but is part
of the language itself.
parseFloat parses its argument, a string, and attempts to return a floating point number. If it encounters a charac-
ter other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns the value up to that
point and ignores that character and all succeeding characters.
If the first character cannot be converted to a number, parseFloat returns one of the following values:
• 0 on Windows platforms.
• "NaN" on any other platform, indicating that the value is not a number.
For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN function to deter-
mine if the result of parseFloat is "NaN". If "NaN" is passed on to arithmetic operations, the operation results will
also be "NaN".
Examples
parseFloat("3.14")
parseFloat("314e-2")
parseFloat("0.0314E+2")
var x = "3.14"
parseFloat(x)
111
The following example returns ”NaN” or 0:
parseFloat("FF2")
See also
parseInt function
Parses a string argument and returns an integer of the specified radix or base.
Syntax
parseInt(string, radix)
Description
The parseInt function is a built-in JavaScript function. It is not a method associated with any object, but is
part of the language itself.
The parseInt function parses its first argument, a string, and attempts to return an integer of the specified
radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8 octal, 16 hexadecimal,
and so on. For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example,
for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding
characters and returns the integer value parsed up to that point. ParseInt truncates numbers to integer values.
If the first character cannot be converted to a number, parseFloat returns one of the following values:
• 0 on Windows platforms.
• "NaN" on any other platform, indicating that the value is not a number.
For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN function to deter-
mine if the result of parseInt is "NaN". If "NaN" is passed on to arithmetic operations, the operation results will
also be "NaN".
Examples
parseInt("F", 16)
parseInt("17", 8)
parseInt("15", 10)
parseInt(15.99, 10)
parseInt("FXX123", 16)
parseInt("1111", 2)
112
parseInt("15*3", 10)
parseInt("Hello", 8)
parseInt("0x7", 10)
parseInt("FFF", 10)
See also
pow method
Returns base to the exponent power, that is, baseexponent.
Syntax
pow(base, exponent)
Applies to
Math
Examples
See also
prompt method
Displays a Prompt dialog box with a message and an input field.
Syntax
prompt(message, [inputDefault])
113
message is any string or a property of an existing object; the string is displayed as the message.
inputDefault is a string or integer that represents the default value of the input field.
Description
Use the prompt method to display a dialog box that receives user input. If you do not specify an initial value for
inputDefault, the dialog box displays the value <undefined>.
Applies to
window
Examples
See also
random method
Returns a pseudo-random number between zero and one. This method is available on X-platforms only.
Syntax
Math.random()
Applies to
Math
Examples
round method
Returns the value of the argument rounded to the nearest integer. If the decimal portion of the argument is .5 or
greater, the argument is rounded to the next highest integer. If the decimal portion of the argument is less than .5,
the argument is rounded to the next lowest integer.
Syntax
round(number)
114
number is any numeric expression.
Applies to
Math
Examples
select method
Selects the input area of the specified object.
Syntax
1. passwordName.select()
2. textName.select()
3. textareaName.select()
passwordName is either the value of the NAME attribute of a password object or an element in the elements
array.
textName is either the value of the NAME attribute of a text object or an element in the elements array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.
Description
Use the select method to highlight the input area of a form element. You can use the select method with the focus
method to highlight a field and position the cursor for a user response.
Applies to
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 focus method returns focus to it
115
so the user can re-enter the password.
function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
userPass.focus()
userPass.select()
}
}
See also
setDate method
Sets the day of the month for a date object.
Syntax
dateObjectName.setDate(dayValue)
Applies to
Date
Examples
The second statement below changes the day for theBigDay to the 24th of July from its original value.
See also
• getDate method
setHours method
Sets the hours in the current time.
116
Syntax
dateObjectName.setHours(hoursValue)
Applies to
Date
Examples
theBigDay.setHours(7)
See also
• getHours method
setMinutes method
Sets the minutes in the current time.
Syntax
dateObjectName.setMinutes(minutesValue)
Applies to
Date
Examples
theBigDay.setMinutes(45)
See also
• getMinutes method
setMonth method
Sets the month in the current date.
117
Syntax
dateObjectName.setMonth(monthValue)
Applies to
Date
Examples
theBigDay.setMonth(6)
See also
• getMonth method
setSeconds method
Sets the seconds in the current time.
Syntax
dateObjectName.setSeconds(secondsValue)
Applies to
Date
Examples
theBigDay.setSeconds(30)
See also
• getSeconds method
setTime method
Sets the value of a date object.
118
Syntax
dateObjectName.setTime(timevalue)
Description
Use the setTime method to help assign a date and time to another date object.
Applies to
Date
Examples
See also
• getTime method
setTimeout method
Evaluates an expression after a specified number of milliseconds have elapsed.
Syntax
timeoutID=setTimeout(expression, msec)
timeoutID is an identifier that is used only to cancel the evaluation with the clearTimeout method.
expression is a string expression.
msec is a numeric value or numeric string in millisecond units.
Description
The setTimeout method evaluates an expression after a specified amount of time. It does not evaluate the
expression repeatedly. For example, if a setTimeout method specifies 5 seconds, the expression is evalu-
ated after 5 seconds, not every 5 seconds.
Applies to
window
119
Examples
The following example displays an alert message 5 seconds (5,000 milliseconds) after the user clicks a button. If
the user clicks the second button before the alert message is displayed, the timeout is cancelled 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>
The following example displays the current time in a text object. The showtime() function, which is called
recursively, uses the setTimeout method update the time every second.
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var timerID = null
var timerRunning = false
function stopclock(){
// cannot directly test timerID on DEC OSF/1 in beta 4.
if(timerRunning)
clearTimeout(timerID)
timerRunning = false
}
function startclock(){
// Make sure the clock is stopped
stopclock()
showtime()
}
function showtime(){
var now = new Date()
var hours = now.getHours()
var minutes = now.getMinutes()
var seconds = now.getSeconds()
var timeValue = "" + ((hours > 12) ? hours - 12 : hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue
timerID = setTimeout("showtime()",1000)
timerRunning = true
120
}
//-->
</SCRIPT>
</HEAD>
<BODY onLoad="startclock()">
<FORM NAME="clock" onSubmit="0">
<INPUT TYPE="text" NAME="face" SIZE=12 VALUE ="">
</FORM>
</BODY>
See also
• clearTimeout method
setYear method
Sets the year in the current date.
Syntax
dateObjectName.setYear(yearValue)
Applies to
Date
Examples
theBigDay.setYear(96)
See also
• getYear method
sin method
Returns the sine of its argument.
Syntax
Math.sin(number)
number is a numeric expression representing the size of an angle in radians. The sin method returns a numeric
121
value between -1 and 1, which represents the sine of the angle.
Applies to
Math
Examples
See also
small method
Causes the calling string object to be displayed in a small font by surrounding it with the HTML font tags
<SMALL>...</SMALL>.
Syntax
stringName.small()
Description
Use the small method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
The following example uses string methods to change the size of a string:
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))
122
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
sqrt method
Returns the square root of its argument.
Syntax
Math.sqrt(number)
number is any non-negative numeric expression. If the value of number is outside the suggested range, the
return value is always 0.
Applies to
Math
Examples
strike method
Causes the calling string object to be displayed as struck out text by surrounding it with the HTML tags
<STRIKE> and </STRIKE>.
Syntax
stringName.strike()
Description
123
Use the strike method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
The following example uses string methods to change the formatting of a string:
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>
See also
sub method
Causes the calling string object to be displayed as a subscript by surrounding it with the HTML tags
<SUB> and </SUB>.
Syntax
stringName.sub()
Description
Use the sub method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
124
The following example uses the sub and sup methods to format a string:
var superText="superscript"
var subText="subscript"
The previous example produces the same output as the following HTML:
See also
• sup method
.ekil
submit method
Submits a form.
Syntax
formName.submit()
Description
The submit method submits the specified form. It performs the same action as a submit button.
Applies to
form
Examples
document.musicChoice.submit()
If musicChoice is the first form created, you also can submit it as follows:
document.forms[0].submit()
See also
• submit object
125
substring method
The substring method returns a subset of a string object.
Syntax
stringName.substring(indexA, indexB)
Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of
the last character is stringName.length - 1.
If indexA is less than indexB, the substring method returns the subset starting with the character at indexA
and ending with the character before indexB. If indexA is greater than indexB, the substring method
returns the subset starting with the character at indexB and ending with the character before indexA. If
indexA is equal to indexB, the substring method returns the empty string.
Applies to
string
Examples
The following example uses substring to display characters from the string "Netscape".
var anyString="Netscape"
//Displays "Net"
document.write(anyString.substring(0,3))
document.write(anyString.substring(3,0))
//Displays "cap"
document.write(anyString.substring(4,7))
document.write(anyString.substring(7,4))
sup method
Causes the calling string object to be displayed as a superscript by surrounding it with the HTML tags
<SUP> and </SUP>.
Syntax
stringName.sup()
stringName is the name of any string variable.
126
Description
Use the sup method with the write or writeln methods to format and display a string in a document.
Applies to
string
Examples
The following example uses the sub and sup methods to format a string:
var superText="superscript"
var subText="subscript"
The previous example produces the same output as the following HTML:
See also
• sub method
tan method
Returns the tangent of its argument.
Syntax
Math.tan(number)
number is a numeric expression representing the size of an angle in radians. The tan method returns a
numeric which represents the tangent of the angle.
Applies to
Math
Examples
See also
toGMTString method
Converts a date to a string, using the Internet GMT conventions.
Syntax
dateObjectName.toGMTString()
Applies to
Date
Examples
today.toGMTString()
In this example, toGMTString converts the date to GMT (UTC) using the operating system's time zone offset and
returns a string value in the following form:
See also
• toLocaleString method
toLocaleString method
Converts a date to a string, using the locale conventions.
Syntax
dateObjectName.toLocaleString()
Applies to
128
Date
Examples
today.toLocaleString()
12/18/95 17:28:35
See also
• toGMTString method
toLowerCase method
Converts the calling string to lower case.
Syntax
stringName.toLowerCase()
Applies to
string
Examples
var upperText="ALPHABET"
document.write(upperText.toLowerCase())
"ALPHABET".toLowerCase
See also
• toUpperCase method
toString method
Converts the value of a Date object or the current location object to a string.
Syntax
129
1. dateObjectName.getDate()
2. location.toString()
Description
The value returned by the method location.toString() is the same as the value of the property location.href.
Applies to
Examples
theBigDay.toString()
toUpperCase method
Converts the calling string to upper case.
Syntax
stringName.toUpperCase()
Applies to
string
Examples
var lowerText="alphabet"
document.write(lowerText.toUpperCase())
"alphabet".toUpperCase
130
See also
• toLowerCase method
unEscape function
Returns the ASCII character for the specified value.
Syntax
unescape(string)
string is a string of the form "%xx", where xx is a number between 0 and 255 (decimal) or 0x0 and 0xFF
(hexadecimal).
Description
The escape function is a built-in JavaScript function. It is not a method associated with any object, but is
part of the language itself.
The string returned by the unescape function is a non-alphanumeric character in the ISO Latin-1 character set.
Examples
unescape("%26")
See also
• escape function
UTC method
Returns the number of milliseconds in a date object since January 1, 1970 00:00:00, Universal Coordi-
nated Time (GMT).
Syntax
UTC takes comma-delimited date parameters and returns the number of milliseconds since January 1, 1970
00:00:00, Universal Coordinated Time (GMT).
Because UTC is a static method of Date, you always use it as Date.UTC(), rather than as a method of a date
object you created.
Applies to
Date
Examples
The following statement creates a date object using GMT instead of local time:
See also
• parse method
write method
Writes one or more HTML expressions to a document in the specified window.
Syntax
Description
The write method displays any number of expressions in a document window. You can specify any
JavaScript expression with the write method, including numerics, strings, or logicals.
The write method is the same as the writeln method, except the write method does not append a newline
character to the end of the output.
Use the write method within any <SCRIPT> tag or within an event handler. Event handlers execute after
the original document closes, so the write method will implicitly open a new document of mimeType text/html
if you do not explicitly issue a document.open() method in the event handler.
Applies to
132
document
Examples
In the following example, the write method takes several arguments, including strings, a numeric, and a variable:
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.
See also
writeln method
Writes one or more HTML expressions to a document in the specified window and follows them with a
newline character.
Syntax
Description
The writeln method displays any number of expressions in a document window. You can specify any
JavaScript expression, including numerics, strings, or logicals.
The writeln method is the same as the write method, except the writeln method appends a newline charac-
ter to the end of the output.
Use the writeln method within any <SCRIPT> tag or within an event handler. Event handlers execute after
the original document closes, so the writeln method will implicitly open a new document of mimeType
text/html if you do not explicitly issue a document.open() method in the event handler.
133
Applies to
document
Examples
All the examples used for the write method are also valid with the writeln method.
See also
134
Properties
The following properties are available in JavaScript:
action property
A string specifying the URL of the server to which form field input information is sent.
Syntax
formName.action
Description
The action property is a reflection of the ACTION attribute of the HTML FORM tag. You can set this property
before or after the HTML source has been through layout.
Applies to
form
Examples
The following example sets the action property of the musicForm form to the value of the variable urlName:
document.musicForm.action=urlName
See also
• method, target properties
135
alinkColor property
The color of an active link (after mouse-button down, but before mouse-button up).
Syntax
document.alinkColor
Description
The alinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in the
Color Appendix. This property is the JavaScript reflection of the ALINK attribute of the HTML 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 hexa-
decimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".
Applies to
document
Examples
The following example sets the color of active links to aqua using a string literal:
document.alinkColor="aqua"
The following example sets the color of active links to aqua using a hexadecimal triplet:
document.alinkColor="00FFFF"
See also
anchors property
xxx
Syntax
xxx
Description
Array of objects corresponding to named anchors (<A NAME=""> tags) in source order.
The anchors array contains an entry for each anchor in a document. For example, if a document contains three
136
anchors, these anchors are reflected as document.anchors[0], document.anchors[1], and
document.anchors[2].
To obtain the number of anchors in a document, use the length property: document.anchors.length.
Applies to
document
Examples
See also
appCodeName property
A string specifying the code name of the browser.
Syntax
navigator.appCodeName
Description
Applies to
navigator
Examples
The following example displays the value of the appCodeName property:
See also
137
appName property
A string specifying the name of the browser.
Syntax
navigator.appName
Description
Applies to
navigator
Examples
See also
appVersion property
A string specifying version information for the Navigator.
Syntax
navigator.appVersion
Description
Applies to
navigator
Examples
See also
• appName, appCodeName, userAgent properties
bgColor property
The color of the document background.
Syntax
document.bgColor
Description
The bgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in the Color
Appendix. This property is the JavaScript reflection of the BGCOLOR attribute of the HTML BODY tag. The
default value of this property is set by the user on the colors tab of the Preferences dialog box, which is displayed
by choosing General Preferences from the Options menu. You can set this property before or 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 hexa-
decimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".
Applies to
document
Examples
139
The following example sets the color of the document background to aqua using a string literal:
document.bgColor="aqua"
The following example sets the color of the document background to aqua using a hexadecimal triplet:
document.bgColor="00FFFF"
See also
checked property
A Boolean value specifying the selection state of a checkbox or radio element.
Syntax
1. checkboxName.checked
2. radioName[index].checked
Description
If a checkbox or radio element is selected, the value of the checked property is true; otherwise, it is false.
You can set the checked property at any time. The display of the checkbox element updates immediately when
you set the checked property.
Applies to
checkbox, radio
Examples
The following example examines an array of radio elements called musicType on the musicForm form to deter-
mine which button is selected. The VALUE attribute of the selected button is assigned to the checkedButton
variable.
function stateChecker() {
var i = ""
var checkedButton = ""
for (i in document.musicForm.musicType) {
if (document.musicForm.musicType[i].checked=="1") {
140
checkedButton=document.musicForm.musicType[i].value
}
}
}
See also
• defaultChecked property
cookie property
String value of a cookie, which is a small piece of information stored by the Navigator in the cookies.txt file.
Syntax
document.cookie
Description
Use string methods such as substring, charAt, indexOf, and lastIndexOf to determine the value stored in the
cookie. See the Netscape cookie specification for a complete specification of the cookie syntax.
Applies to
document
Examples
The following function uses the cookie property to record a reminder for users of an application. The "expires="
component sets an expiration date for the cookie, so it persists beyond the current browser session.
When the user loads the page that contains this function, another function uses indexOf("@") and indexOf("=") to
determine the date and time stored in the cookie.
See Also
• hidden object
141
defaultChecked property
A Boolean value indicating the default selection state of a checkbox or radio element.
Syntax
1. checkboxName.defaultChecked
2. radioName[index].defaultChecked
Description
If an checkbox or radio element is selected by default, the value of the defaultChecked property is true; other-
wise, it is false. defaultChecked initially reflects whether the HTML CHECKED attribute is used within an
INPUT tag; however, setting defaultChecked may override the CHECKED attribute.
You can set the defaultChecked property at any time. The display of the checkbox element does not update when
you set the defaultChecked property, only when you set the checked property.
Applies to
checkbox, radio
Examples
The following example resets an array of radio elements called musicType on the musicForm form to the default
selection state.
function radioResetter() {
var i=""
for (i in document.musicForm.musicType) {
if (document.musicForm.musicType[i].defaultChecked==true) {
document.musicForm.musicType[i].checked=true
}
}
}
See also
checked property
defaultSelected property
A Boolean value indicating the default selection state of an option in a select element.
142
Syntax
selectName.options[index].defaultSelected
Description
If an option in a select element is selected by default, the value of the defaultSelected property is true; otherwise,
it is false. defaultSelected initially reflects whether the HTML SELECTED attribute is used within an OPTION
tag; however, setting defaultSelected may override the SELECTED attribute.
Applies to
options property
Examples
In the following example, the restoreDefault() function returns the musicType element to its default state. The for
loop evaluates every option in the select element. The if statement sets the selected property if defaultSelected is
true.
function restoreDefault() {
for (var i = 0; i < document.musicForm.musicType.length; i++) {
if (document.musicForm.musicType.options[i].defaultSelected == true) {
document.musicForm.musicType.options[i].selected=true
}
}
}
The previous example assumes that the select element is similar to the following:
<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>
See also
defaultStatus property
The default message displayed in the status bar at the bottom of the window.
143
Syntax
windowReference.defaultStatus
Description
The defaultStatus message appears when nothing else is in the status bar. Do not confuse the defaultStatus
property with the status property. The status property reflects a priority or transient message in the status bar,
such as the message that appears when a mouseOver event occurs over an anchor.
You can set the defaultStatus property at any time. You must return true if you want to set the defaultStatus
property in the onMouseOver event handler.
Applies to
window
Examples
In the following example, the statusSetter() function sets both the status and defaultStatus properties in an
onMouseOver event handler:
function statusSetter() {
window.defaultStatus = "Click the link for the Netscape home page"
window.status = "Netscape home page"
}
In the previous example, notice that the onMouseOver event handler returns a value of true. You must return true
to set status or defaultStatus in an event handler.
See also
• status property
defaultValue property
xxx
Syntax
xxx
Description
144
For hidden, password, text, and textarea, string, the initial contents of the field.
Applies to
Examples
See also
• value property
E property
Euler's constant and the base of natural logarithms, approximately 2.718.
Syntax
Math.E
Description
Applies to
Math
Examples
See also
elements property
xxx
Syntax
145
xxx
Description
Array of objects corresponding to form elements (such as checkbox, radio, and text objects) in source order.
The elements array contains an entry for each object in a form. For example, if a form has a text field, a radio
button group, and a checkbox, these elements are reflected as formName.elements[0],
formName.elements[1], and
formName.elements[2].
Applies to
form
Examples
encoding property
A string specifying the MIME encoding of the form.
Syntax
formName.encoding
Description
The encoding property is a reflection of the ENCTYPE attribute of the HTML FORM tag.
Applies to
form
Examples
xxx To be supplied
See also
xxx To be supplied
146
fgColor property
The color of the document foreground text.
Syntax
document.fgColor
Description
The fgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in the Color
Appendix. This property is the JavaScript reflection of the FGCOLOR attribute of the HTML BODY tag. The
default value of this property is set by the user on the colors tab of the Preferences dialog box, which is displayed
by choosing General Preferences from the Options menu. You cannot set this property after the HTML source
has been through layout.
If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexa-
decimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".
Applies to
document
Examples
The following example sets the color of the foreground to aqua using a string literal:
document.fgColor="aqua"
The following example sets the color of the foreground to aqua using a hexadecimal triplet:
document.fgColor="00FFFF"
See also
forms property
xxx
Syntax
xxx
Description
147
Array of objects corresponding to named forms (<FORM NAME=""> tags) in source order.
The forms array contains an entry for each form object in a document. For example, if a document contains three
forms, these forms are reflected as document.forms[0], document.forms[1], and document.forms[2].
You can refer to a form's elements by using the forms array. For example, you would refer to a text object named
quantity in the second form as:
document.forms[1].quantity
You would refer to the value property of this text object as:
document.forms[1].quantity.value
To obtain the number of forms in a document, use the length property: document.forms.length.
Applies to
document
Examples
See also
• length property
frames property
xxx
Syntax
xxx
Description
Array of objects corresponding to child frame windows (<FRAMESET> tag) in source order.
The frames array contains an entry for each child frame in a window. For example, if a window contains
three child frames, these frames are reflected as window.frames[0], window.frames[1], and
window.frames[2].
To obtain the number of number of child frames in a window, use the length property:
window.frames.length.
148
Applies to
window
Examples
See also
• length property
hash property
A string beginning with a hash mark (#) that specifies an anchor name fragment in the URL.
Syntax
location.hash
Description
You can set the hash property at any time, although it is safer to set the href property to change a location. If the
hash that you specify cannot be found in the current location, you will get an error.
See RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hash.
Applies to
location
Examples
See also
host property
A string specifying the hostname:port portion of the URL.
149
Syntax
location.host
Description
The host property specifies a portion of the URL. The host property is the concatenation of the hostname and
port properties, separated by a colon. When the port property is null, the host property is the same as the
hostname property.
You can set the host property at any time, although it is safer to set the href property to change a location. If the
host that you specify cannot be found in the current location, you will get an error.
See Section 3.1 of RFC 1738 for complete information about the hostname and port.
Applies to
location
Examples
See also
hostname property
A string specifying the domain name or IP address of a network host.
Syntax
location.hostname
Description
The hostname property specifies a portion of the URL. The hostname property is a substring of the host property.
The host property is the concatenation of the hostname and port properties, separated by a colon. When the port
property is null, the host property is the same as the hostname property.
You can set the hostname property at any time, although it is safer to set the href property to change a location. If
the hostname that you specify cannot be found in the current location, you will get an error.
See Section 3.1 of RFC 1738 for complete information about the hostname.
150
Applies to
location
Examples
See also
href property
A string specifying the entire URL.
Syntax
location.href
Description
The href property specifies the entire URL. Other location object properties are substrings of the href property.
You can set the href property at any time.
Applies to
location
Examples
In the following example, the window.open statement creates a window called newWindow and loads the
specified URL into it. The document.write statements display all the properties of newWindow.location in a
window called msgWindow.
newWindow=window.open("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object")
newWindow.location.href = http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.protocol = http:
newWindow.location.host = home.netscape.com
newWindow.location.hostName = home.netscape.com
newWindow.location.port =
newWindow.location.pathname = /comprod/products/navigator/version_2.0/script/
script_info/objects.html
newWindow.location.search =
newWindow.location.hash = #checkbox_object
See also
index property
An integer representing the index of a radio element or an option in a select element.
Syntax
1. radioName.index
2. selectName.options[indexValue].index
Description
For radio, number, the ordinal number of the radio field, 0-based. For a select object option, the number identify-
ing the position of the option in the selection, starting from zero.
Applies to
Examples
152
See also
For options:
• defaultSelected, selected, selectedIndex properties
lastModified property
A string representing the date that a document was last modified.
Syntax
document.lastModified
Description
Applies to
document
Examples
In the following example, the value of the lastModified property is assigned to a variable called currentDate:
length property
xxx
Syntax
xxx
Description
For a history object, the length of the history list. For a string object, the integer length of the string. For a radio
object, the number of radio buttons in the object. For an anchors, forms, frames, links, or options array, the
number of elements in the array. For a select element, the number of options in the element.
153
Applies to
• history, radio, select, string objects
• anchors, forms, frames, links, options properties
Examples
If the string object mystring is "netscape", then mystring.length returns the integer 8.
If the current document contains five forms, then document.forms.length returns the integer 5.
linkColor property
The color of the document hyperlinks.
Syntax
document.linkColor
Description
The linkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in the
Color Appendix. This property is the JavaScript reflection of the LINK attribute of the HTML BODY tag. The
default value of this property is set by the user on the colors tab of the Preferences dialog box, which is displayed
by choosing General Preferences from the Options menu. You cannot set this property after the HTML source
has been through layout.
If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexa-
decimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".
Applies to
document
Examples
The following example sets the color of document links to aqua using a string literal:
document.linkColor="aqua"
The following example sets the color of document links to aqua using a hexadecimal triplet:
document.linkColor="00FFFF"
See also
Syntax
xxx
Description
Array of objects corresponding to link objects (<A HREF=URL> tags) in source order.
The links array contains an entry for each link object in a document. For example, if a document contains
three link objects, these links are reflected as document.links[0], document.links[1], and
document.links[2].
To obtain the number of links in a document, use the length property: document.links.length.
Applies to
document
Examples
See also
LN2 property
The natural logarithm of two, approximately 0.693.
Syntax
Math.LN2
Description
Applies to
Math
155
Examples
See also
LN10 property
The natural logarithm of ten, approximately 2.302.
Syntax
Math.LN10
Description
Applies to
Math
Examples
See also
location property
A string specifying the complete URL of the document.
Syntax
document.location
Description
156
Do not confuse the location object with the location property of the document object. The location object has
properties with values you can change, and the location property does not. document.location is a string-
valued property that usually matches what window.location is set to when you load the document, but redirec-
tion may change it.
Applies to
document
Examples
The following example displays the URL of the current document:
See also
• location object
method property
A string specifying how form field input information is sent to the server.
Syntax
formName.method
Description
The method property is a reflection of the METHOD attribute of the HTML FORM tag. You cannot set this
property after the HTML source has been through layout. The method property can evaluate to either "get" or
"post". See the form object for more information.
Applies to
form
Examples
The following example sets the method property of the musicInfo form to "post":
musicInfo.method="post"
See also
• action, target properties
157
name property
xxx
Syntax
xxx
Description
A string whose value is the same as the NAME attribute of the object. Note that for button, reset, and
submit objects, this is the internal name for the button, not the label that appears onscreen.
Applies to
• button, checkbox, hidden, password, radio, reset, select, submit, text, textarea
Examples
See also
• value property
options property
xxx
Syntax
xxx
Description
Array of objects corresponding to options in a select object (<OPTION> tags) in source order.
The options array contains an entry for each option in a select object. For example, if a select object named
musicStyle contains three options, these options are reflected as musicStyle.options[0],
musicStyle.options[1], and musicStyle.options[2].
To obtain the number of options in a select object, use the length property of the select object:
selectName.length.
Applies to
select
158
Properties
• defaultSelected
• index
• selected reflects the SELECTED argument
• text
• value
Examples
See also
• length property
parent property
xxx
Syntax
xxx
Description
Applies to
window
Examples
pathname property
A string specifying the url-path portion of the URL.
Syntax
location.pathname
Description
159
The pathname property specifies a portion of the URL. The pathname supplies the details of how the specified
resource can be accessed.
You can set the pathname property at any time, although it is safer to set the href property to change a location. If
the pathname that you specify cannot be found in the current location, you will get an error.
See Section 3.1 of RFC 1738 for complete information about the pathname.
Applies to
location
Examples
See also
PI property
The ratio of the circumference of a circle to its diameter, approximately 3.1415.
Syntax
Math.PI
Description
Applies to
Math
Examples
See also
160
port property
A string specifying the port number to connect to, if any.
Syntax
location.port
Description
The port property specifies a portion of the URL. The port property is a substring of the host property. The host
property is the concatenation of the hostname and port properties, separated by a colon. When the port property
is null, 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.
See Section 3.1 of RFC 1738 for complete information about the port.
Applies to
location
Examples
See also
protocol property
A string specifying the beginning of the URL, up to and including the first colon.
Syntax
location.protocol
Description
The protocol property specifies a portion of the URL. The protocol indicates the access method of the URL. For
example, a protocol of "http:" specifies Hypertext Transfer Protocol, and a protocol of "javascript:" specifies
JavaScript code.
You can set the protocol property at any time, although it is safer to set the href property to change a location. If
the protocol that you specify cannot be found in the current location, you will get an error.
161
The protocol property represents the scheme name of the URL. See Section 2.1 of RFC 1738 for complete
information about the protocol.
Applies to
location
Examples
See also
referrer property
xxx
Syntax
xxx
Description
document
Examples
search property
A string beginning with a question mark that specifies any query information in the URL.
Syntax
location.search
Description
See Section 3.3 of RFC 1738 for complete information about the search.
Applies to
location
Examples
In the following example, the window.open statement creates a window called newWindow and loads the
specified URL into it. The document.write statements display all the properties of newWindow.location in a
window called msgWindow.
newWindow=window.open("http://guide-p.infoseek.com/WW/NS/
Titles?qt=RFC+1738+&col=WW")
msgWindow.document.write("newWindow.location.href = " + newWindow.location.href +
"<P>")
msgWindow.document.write("newWindow.location.protocol = " +
newWindow.location.protocol + "<P>")
msgWindow.document.write("newWindow.location.host = " + newWindow.location.host +
"<P>")
msgWindow.document.write("newWindow.location.hostName = " +
newWindow.location.hostName + "<P>")
msgWindow.document.write("newWindow.location.port = " + newWindow.location.port +
"<P>")
msgWindow.document.write("newWindow.location.pathname = " +
newWindow.location.pathname + "<P>")
msgWindow.document.write("newWindow.location.search = " +
newWindow.location.search + "<P>")
msgWindow.document.write("newWindow.location.hash = " + newWindow.location.hash +
"<P>")
msgWindow.document.close()
newWindow.location.href = http://guide-p.infoseek.com/WW/NS/
Titles?qt=RFC+1738+&col=WW
newWindow.location.protocol = http:
newWindow.location.host = guide-p.infoseek.com
newWindow.location.hostName = guide-p.infoseek.com
newWindow.location.port =
newWindow.location.pathname = /WW/NS/Titles
newWindow.location.search = ?qt=RFC+1738+&col=WW
newWindow.location.hash =
See also
163
selected property
A Boolean value specifying the current selection state of an option in a select object.
Syntax
selectName.options[index].selected
Description
If an option in a select element is selected, the value of its selected property is true; otherwise, it is false.
You can set the selected property at any time. The display of the select element updates immediately when you
set the selected property.
In general, the selected property is more useful than the selectedIndex property for select elements that are
created with the MULTIPLE attribute. With the selected property, you can evaluate every option in the options
array to determine multiple selections, and you can select individual options without clearing the selection of other
options.
Applies to
options property
Examples
See also
• defaultSelected property
selectedIndex property
An integer specifying the index of the selected item.
Syntax
selectName.selectedIndex
Description
164
Options in a select element 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 form element updates immediately when you set the
selectedIndex property.
In general, the selectedIndex property is more useful for select elements 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 element.
The selected property of the select element's options array is more useful for select elements that are created with
the MULTIPLE attribute. With the selected property, you can evaluate every option in the options array to
determine multiple selections, and you can select individual options without clearing the selection of other options.
Applies to
select
Examples
In the following example, the getSelectedIndex() function assigns the selected index in themusicType element to
the variable chosenIndex :
function getSelectedIndex() {
var chosenIndex=""
chosenIndex=document.musicForm.musicType.selectedIndex
}
The previous example assumes that the select element is similar to the following:
<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>
See also
self property
The self property refers to the current window.
Syntax
xxx
Description
The self property refers to the current window. Use the self property to disambiguate a window property from a
165
form of the same name. You can also use the self property to make your code more readable.
Applies to
window
Examples
In the following example, self.status is used to set the status property. This usage disambiguates the status
property of a window from a form called "status".
<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="self.status='Pick a random URL' ; return true">
Go!</A>
See also
• window property
SQRT1_2 property
The square root of one-half; equivalently, one over the square root of two, approximately 0.707.
Syntax
Math.SQRT1_2
Description
Applies to
Math
Examples
See also
166
SQRT2 property
The square root of two, approximately 1.414.
Syntax
Math.SQRT2
Description
Applies to
Math
Examples
See also
status property
Specifies a priority or transient message in the status bar at the bottom of the window, such as the message that
appears when a mouseOver event occurs over an anchor.
Syntax
windowReference.status
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.
Applies to
167
window
Examples
Suppose you have created a JavaScript function called pickRandomURL() that lets you select a URL at random.
You can use the onClick event handler of an anchor to specify a value for the HREF attribute of the anchor
dynamically, and the onMouseOver event handler to specify a custom message for the window in the status
property:
<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="self.status='Pick a random URL'; return true">
Go!</A>
In the above example, the status property of the window is assigned to the window's self property, as self.status.
As this example shows, you must return true to set the status property in the onMouseOver event handler.
See also
• defaultStatus property
target property
For form, a string specifying the name of the window that responses go to after a form has been submitted. For
link, a string specifying the name of the window that displays the content of a clicked hypertext link.
Syntax
1. formName.target
2. linkName.target
Description
The target property is a reflection of the TARGET attribute of the HTML FORM and A tags. You can set this
property before or after the HTML source has been through layout.
Applies to
form, link
Examples
The following example specifies that responses to the musicInfo form are displayed in the "msgWindow" window:
document.musicInfo.target="msgWindow"
168
See also
For form:
• action, method properties
text property
xxx
Syntax
xxx
Description
Applies to
select
Examples
title property
A string representing the title of a document.
Syntax
document.title
Description
The title property is a reflection of the value specified within the <TITLE> and </TITLE> tags. If a document
does not have a title, the title property is null.
Applies to
document
169
Examples
In the following example, the value of the title property is assigned to a variable called <I>docTitle</I>:
top property
xxx
Syntax
xxx
Description
Applies to
window
Examples
userAgent property
A string representing the value of the user-agent header sent in the HTTP protocol from client to server.
Syntax
navigator.userAgent
Description
Servers use the value sent in the user-agent header to identify the client.
Applies to
navigator
170
Examples
See also
value property
For button, reset, and submit objects, a string that is the same as the VALUE attribute (this is the label that
appears onscreen, not the internal name for the button). For checkbox, a string, "on" if item is checked; "off"
otherwise. For radio, a string, reflection of the VALUE attribute. For select objects, reflection of VALUE at-
tribute, sent to server on submit. For hidden, text, textarea, and string, the contents of the field.
Syntax
xxx
Description
For button, reset, and submit objects, a string that is the same as the VALUE attribute (this is the label that
appears onscreen, not the internal name for the button). For checkbox, a string, "on" if item is checked; "off"
otherwise. For radio, a string, reflection of the VALUE attribute. For select objects, reflection of VALUE at-
tribute, sent to server on submit. For text and textarea, string, the contents of the field.
If you change the value property of a text or textArea object, the object on the form is updated dynami-
cally. If you change the value property of any other type of object, the object on the form is not updated.
Applies to
button, checkbox, hidden, password, radio, reset, select, submit, text, textarea
Examples
xxx Examples to be supplied.
See also
171
vlinkColor property
The color of visited links.
Syntax
document.vlinkColor
Description
The vlinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in the
Color Appendix. This property is the JavaScript reflection of the VLINK attribute of the HTML BODY tag. The
default value of this property is set by the user on the colors tab of the Preferences dialog box, which is displayed
by choosing General Preferences from the Options menu. You cannot set this property after the HTML source
has been through layout.
If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexa-
decimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".
Applies to
document
Examples
The following example sets the color of visited links to aqua using a string literal:
document.vlinkColor="aqua"
The following example sets the color of active links to aqua using a hexadecimal triplet:
document.vlinkColor="00FFFF"
See also
window property
xxx
Syntax
xxx
Description
172
The window property refers to the current window. Use the window property to disambiguate a property
of the window object from a form of the same name. You can also use the window property to make your code
more readable.
Applies to
window
Examples
In the following example, window.status is used to set the status property. This usage disambiguates the status
property of a window from a form called "status".
<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="window.status='Pick a random URL' ; return true">
Go!</A>
See also
self property
173
Event handlers
The following event handlers are available in JavaScript:
• onBlur
• onChange
• onClick
• onFocus
• onLoad
• onMouseOver
• onSelect
• onSubmit
• onUnload
Applies to
Examples
In the following example, userName is a required text field. When a user attempts to leave the field, the
onBlur event handler calls the required() function to confirm that userName has a legal value.
See also
Use the onChange event handler to validate data after it is modified by a user.
174
Applies to
Examples
In the following example, userName is a text field. When a user attempts to leave the field, the onBlur
event handler calls the checkValue() function to confirm that userName has a legal value.
See also
Applies to
Examples
For example, suppose you have created a JavaScript function called compute(). You can execute the
compute() function when the user clicks a button by calling the function in the onClick event handler, as
follows:
In the above example, the keyword this refers to the current object; in this case, the Calculate button. The
construct this.form refers to the form containing the button.
For another example, suppose you have created a JavaScript function called pickRandomURL() that lets
you select a URL at random. You can use the onClick event handler of an anchor to dynamically specify a
value for the HREF attribute of the anchor, as shown in the following example:
<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="window.status='Pick a random URL'; return true">
Go!</A>
In the above example, the onMouseOver event handler specifies a custom message for the Navigator
status bar when the user places the mouse pointer over the Go! anchor. As this example shows, you must
175
return true to set the window.status property in the onMouseOver event handler.
Applies to
Examples
The following example uses an onFocus handler in the valueField textarea object to call the valueCheck()
function.
See also
Use the onLoad event handler within either the <BODY> or the <FRAMESET> tag, for example, <BODY
onLoad="...">.
Applies to
window
Examples
In the following example, the onLoad event handler displays a greeting message after a web page is
loaded.
See also
• onUnload event handler
176
onMouseOver event handler
A mouseOver event occurs when the mouse pointer is over an object. The onMouseOver event handler
executes JavaScript code when a mouseOver event occurs.
You must return true if you want to set the status or defaultStatus properties with the onMouseOver event han-
dler.
Applies to
link
Examples
By default, the HREF value of an anchor displays in the status bar at the bottom of the Navigator when a user
places the mouse pointer over the anchor. In the following example, the onMouseOver event handler provides the
custom message "Click this if you dare."
<A HREF="http://home.netscape.com/"
onMouseOver="window.status='Click this if you dare!'; return true">
Click me</A>
See onClick for an example of using onMouseOver when the anchor HREF attribute is set dynamically.
Applies to
text, textarea
Examples
The following example uses an onSelect handler in the valueField text object to call the selectState()
function.
177
onSubmit event handler
A submit event occurs when a user submits a form. The onSubmit event handler executes JavaScript code when
a submit event occurs.
You must return true in the event handler to allow the form to be submitted; return false to prevent the
form from being submitted.
Applies to
form
Examples
In the following example, the onSubmit event handler calls the badFormData() function to evaluate the data being
submitted. If the data is legal, the form is submitted; otherwise, the form is not submitted.
form.onSubmit="return badFormData(this)"
Use the onLoad event handler within either the <BODY> or the <FRAMESET> tag, for example, <BODY
onLoad="...">.
Applies to
window
Examples
In the following example, the onUnload event handler calls the cleanUp() function to perform some shut
down processing when the user exits a web page:
<BODY onUnload="cleanUp()">
See also
178
Statements
JavaScript statements consist of keywords used with the appropriate syntax. A single statement may span
multiple lines. Multiple statements may occur on a single line if each statement is separated by a semi-
colon.
Syntax conventions : All keywords in syntax statements are in bold. Words in italics represent user-defined
names or statements. Any portions enclosed in square brackets, [ ], are optional. {statements} indicates a
block of statements, which can consist of a single statement or multiple statements delimited by a curly braces {}.
break statement
The break statement terminates the current while or for loop and transfers program control to the state-
ment following the terminated loop.
Syntax
break
Examples
The following function has a break statement that terminates the while loop when i is 3, and then returns the
value 3 * x.
function func(x) {
var i = 0
while (i < 6) {
if (i == 3)
break
i++
}
return i*x
}
comment statement
Comments are notations by the author to explain what the script does, and they are ignored by the interpreter.
JavaScript supports Java-style comments:
• Comments on a single line are preceded by a double-slash (//).
179
• Comments that span multiple lines are preceded by a /* and followed by a */.
Syntax
1. // comment text
2. /* multiple line comment text */
Examples
continue statement
The continue statement terminates execution of the block of statements in a while or for loop, and continues
execution of the loop with the next iteration. In contrast to the break statement, it does not terminate the execu-
tion of the loop entirely: instead,
Syntax
continue
Examples
The following example shows a while loop that has a continue statement that executes when the value of i is 3.
Thus, n takes on the values 1, 3, 7, and 12.
i = 0
n = 0
while (i < 5) {
i++
if (i == 3)
continue
n += i
}
for statement
A for loop consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed
by a block of statements executed in the loop. The parts of the for statement are:
• The initial expression, generally used to initialize a counter variable. This statement may optionally
declare new variables with the var keyword. This expression is optional.
180
• The condition that is evaluated on each pass through the loop. If this condition is true, the statements in
the succeeding block are performed. This conditional test is optional. If omitted, then the condition
always evaluates to true.
• An update expression generally used to update or increment the counter variable. This expres
sion is optional.
• A block of statements that are executed as long as the condition is true. This can be a single statement
or multiple statements. Although not required, it is good practice to indent these statements four spaces
from the beginning of the for statement.
Syntax
Examples
This for statement starts by declaring the variable i and initializing it to zero. It checks that i is less than nine, and
performs the two succeeding statements, and increments i by one after each pass through the loop.
for...in statement
The for statement iterates variable var over all the properties of object obj. For each distinct property, it
executes the statements in statements.
Syntax
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.
181
function statement
The function statement declares a JavaScript function name with the specified parameters param. To return a
value, the function must have a return statement that specifies the value to return. You cannot nest a function
statement in another
statement or in itself.
All parameters are passed to functions, by value. In other words, the value is passed to the function, but if
the function changes the value of the parameter, this change is not reflected globally or in the calling
function.
Syntax
Examples
if...else statement
The if...else statement is a conditional statement that executes the statements in statements if condition is
true. In the optional else clause, it executes the statements in else statements if condition is false. These
may be any JavaScript statements, including further nested if statements.
Syntax
if (condition) {
statements
} [else {
else statements
}]
Examples
if ( cipher_char == from_char ) {
result = result + to_char
x++
} else
result = result + clear_char
182
return statement
The return statement specifies the value to be returned by a function.
Syntax
return expression;
Examples
The following simple function returns the square of its argument, x, where x is an number.
function square( x ) {
return x * x
}
var statement
The var statement declares a variable varname, optionally initializing it to value. The variable name varname
can be any legal identifier, and value can be any legal expression. 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 there is a global variable of the same name.
Syntax
Examples
while statement
The while statement is a loop that evaluates the expression condition, and if it is true, executes statements. It
then repeats this process, as long as condition is true. When condition evaluates to false, execution continues
with the statement following statements.
Although not required, it is good practice to indent the statements a while loop four spaces from the beginning of
a for statement.
Syntax
while (condition) {
statements
}
183
Examples
The following while loop iterates as long as n is less than three. Each iteration, it increments n and adds it to x.
Therefore, x and n take on the following values:
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.
n = 0
x = 0
while( n < 3 ) {
n ++; x += n
}
with statement
The with statement establishes object as the default object for the statements. Any property references
without an object are then assumed to be for object. Note that the parentheses are required around object.
Syntax
with (object){
statements
}
Examples
with (Math) {
a = PI * r*r
x = r * cos(theta)
y = r * sin(theta)
}
184
Reserved words
The reserved words in this list cannot be used as JavaScript variables, functions, methods, or object
names. Some of these words are keywords used in JavaScript; others are reserved for future use.
185
Color values
The string literals in this table can be used to specify colors in the JavaScript alinkColor, bgColor,
fgColor, linkColor, and vlinkColor properties and the fontcolor method.
You can also use these string literals to set the color in the HTML reflections of these properties, for
example <BODY BGCOLOR="bisque">, and to set the COLOR attribute of the FONT tag, for example,
<FONT COLOR="blue">color</font>.
The following red, green, and blue values are in Decimal and Hexidecimal.
Decimal Hexidecimal
Color Red Green Blue Red Green Blue
aliceblue 240 248 255 F0 F8 FF
antiquewhite 250 235 215 FA EB D7
aqua 0 255 255 00 FF FF
aquamarine 127 255 212 7F FF D4
azure 240 255 255 F0 FF FF
beige 245 245 220 F5 F5 DC
bisque 255 228 196 FF E4 C4
black 0 0 0 00 00 00
blanchedalmond 255 235 205 FF EB CD
blue 0 0 255 00 00 FF
blueviolet 138 43 226 8A 2B E2
brown 165 42 42 A5 2A 2A
burlywood 222 184 135 DE B8 87
cadetblue 95 158 160 5F 9E A0
chartreuse 127 255 0 7F FF 00
chocolate 210 105 30 D2 69 1E
coral 255 127 80 FF 7F 50
cornflowerblue 100 149 237 64 95 ED
cornsilk 255 248 220 FF F8 DC
crimson 220 20 60 DC 14 3C
cyan 0 255 255 00 FF FF
darkblue 0 0 139 00 00 8B
darkcyan 0 139 139 00 8B 8B
darkgoldenrod 184 134 11 B8 86 0B
darkgray 169 169 169 A9 A9 A9
darkgreen 0 100 0 00 64 00
darkkhaki 189 183 107 BD B7 6B
darkmagenta 139 0 139 8B 00 8B
darkolivegreen 85 107 47 55 6B 2F
darkorange 255 140 0 FF 8C 00
darkorchid 153 50 204 99 32 CC
darkred 139 0 0 8B 00 00
darksalmon 233 150 122 E9 96 7A
darkseagreen 143 188 143 8F BC 8F
darkslateblue 72 61 139 48 3D 8B
darkslategray 47 79 79 2F 4F 4F
darkturquoise 0 206 209 00 CE D1
186
Decimal Hexidecimal
Color Red Green Blue Red Green Blue
188
PERSISTENT CLIENT STATE
HTTP COOKIES
Preliminary Specification - Use with caution
INTRODUCTION
Cookies are a general mechanism which server side connections (such as CGI scripts) can use to both store and
retrieve information on the client side of the connection. The addition of a simple, persistent, client-side state
significantly extends the capabilities of Web-based client/server applications.
OVERVIEW
A server, when returning an HTTP object to a client, may also send a piece of state information which the client
will store. Included in that state object is a description of the range of URLs for which that state is valid. Any
future HTTP requests made by the client which fall in that range will include a transmittal of the current value of
the state object from the client back to the server. The state object is called a cookie, for no compelling reason.
This simple mechanism provides a powerful new tool which enables a host of new types of applications to be
written for web-based environments. Shopping applications can now store information about the currently se-
lected items, for fee services can send back registration information and free the client from retyping a user-id on
next connection, sites can store per-user preferences on the client, and have the client supply those preferences
every time that site is connected to.
SPECIFICATION
A cookie is introduced to the client by including a Set-Cookie header as part of an HTTP response, typically this
will be generated by a CGI script.
This is the format a CGI script would use to add to the HTTP headers a new piece of data which is to be stored
by the client for later retrieval.
NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need
to place such data in the name or value, some encoding method such as URL style %XX encoding is
recommended, though no encoding is defined or required.
189
expires=DATE
The expires attribute specifies a date string that defines the valid life time of that cookie. Once the
expiration date has been reached, the cookie will no longer be stored or given out.
This is based on RFC 850, RFC 1036, and RFC 822, with the variations that the only legal time zone is
GMT and the separators between the elements of the date must be dashes.
expires is an optional attribute. If not specified, the cookie will expire when the user's session ends.
Note: There is a bug in Netscape Navigator version 1.1 and earlier. Only cookies whose path attribute is
set explicitly to "/" will be properly saved between sessions if they have an expires attribute.
domain=DOMAIN_NAME
When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is
made with the Internet domain name of the host from which the URL will be fetched. If there is a tail
match, then the cookie will go through path matching to see if it should be sent. "Tail matching" means
that domain attribute is matched against the tail of the fully qualifieddomain name of the host. A domain
attribute of "acme.com" would match host names "anvil.acme.com" as well as "shipping.crate.acme.com".
Only hosts within the specified domain can set a cookie for a domain and domains must have at least two
(2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain
that fails within one of the seven special top level domains listed below only require two periods. Any
other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET",
"ORG", "GOV", "MIL", and "INT".
The default value of domain is the host name of the server which generated the cookie response.
path=PATH
The path attribute is used to specify the subset of URLs in a domain for which the cookie is valid. If a
cookie has already passed domain matching, then the pathname component of the URL is compared
with the path attribute, and if there is a match, the cookie is considered valid and is sent along with the
URL request. The path "/foo" would match "/foobar" and "/foo/bar.html". The path "/" is the most general
path.
If the path is not specified, it as assumed to be the same path as the document being described by the
header which contains the cookie.
secure
If a cookie is marked secure, it will only be transmitted if the communications channel with the host is a
secure one. Currently this means that secure cookies will only be sent to HTTPS (HTTP over SSL)
servers.
If secure is not specified, a cookie is considered safe to be sent in the clear over unsecured channels.
190
Syntax of the Cookie HTTP Request Header
When requesting a URL from an HTTP server, the browser will match the URL against all cookies and if any of
them match, a line containing the name/value pairs of all matching cookies will be included in the HTTP request.
Here is the format of that line:
Additional Notes
• Instances of the same path and name will overwrite each other, with the latest instance taking prece
dence. Instances of the same path but different names will add additional mappings.
• Setting the path to a higher-level value does not override other more specific path mappings. If there
are multiple matches for a given cookie name, but with separate paths, all the matching cookies will be
sent. (See examples below.)
• The expires header lets the client know when it is safe to purge the mapping but the client is not re
quired to do so. A client may also delete a cookie before it's expiration date arrives if the number of
cookies exceeds its internal limits.
• When sending cookies to a server, all cookies with a more specific path mapping should be sent before
cookies with less specific path mappings. For example, a cookie "name1=foo" with a path mapping of
"/" should be sent after a cookie "name1=foo2" with a path mapping of "/bar" if they are both to be
sent.
• There are limitations on the number of cookies that a client can store at any one time. This is a specifi
cation of the minimum number of cookies that a client should be prepared to receive and store.
• 300 total cookies
• 4 kilobytes per cookie, where the name and the OPAQUE_STRING combine to form the 4
kilobyte limit.
• 20 cookies per server or domain. (note that completely specified hosts and domains are treated
as separate entities and have a 20 cookie limitation for each, not combined)
Servers should not expect clients to be able to exceed these limits. When the 300 cookie limit or the 20
cookie per server limit is exceeded, clients should delete the least recently used cookie. When a cookie
larger than 4 kilobytes is encountered the cookie should be trimmed to fit, but the name should remain
intact as long as it is less than 4 kilobytes.
• If a CGI script wishes to delete a cookie, it can do so by returning a cookie with the same name, and
an expires time which is in the past. The path and name must match exactly in order for the expiring
cookie to replace the valid cookie. This requirement makes it difficult for anyone but the originator of a
cookie to delete a cookie.
• When caching HTTP, as a proxy server might do, the Set-cookie response header should never be
cached.
• If a proxy server receives a response which contains a Set-cookie header, it should propagate the Set-
191
cookie header to the client, regardless of whether the response was 304 (Not Modified) or 200 (OK).
Similarly, if a client request contains a Cookie: header, it should be forwarded through a proxy, even if
the conditional If-modified-since request is being made.
EXAMPLES
Here are some sample exchanges which are designed to illustrate the use of cookies.
Cookie: CUSTOMER=WILE_E_COYOTE
Client receives:
Client receives:
192
Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
Client receives:
NOTE: There are two name/value pairs named "PART_NUMBER" due to the inheritance of the "/" mapping
in addition to the "/ammo" mapping.
193
JavaScript Snippets
<HTML>
<HEAD>
<TITLE>IPST • Internet Professional Services & Training</TITLE>
<!--Updated 2/6/96-->
<SCRIPT language="JavaScript">
<!--
var timerID = null;
var timerRunning = false;
function stopclock (){
if(timerRunning)
cleartimeout(timerID);
timerRunning=false;
}
function startclock (){
stopclock();
showtime();
}
function showtime (){
var now = new Date();
var dow = now.getDay();
if(dow == 0){
dow = "Sun";
} else {
if(dow == 1){
dow = "Mon";
} else {
if(dow == 2){
dow = "Tues";
} else {
if(dow == 3){
dow = "Wed";
} else {
if(dow == 4){
dow = "Thur";
} else {
if(dow == 5){
dow = "Fri";
} else {
dow = "Sat";
}}}}}}
var month = now.getMonth();
if(month < 10){
month = "0" + month;
}
var date = now.getDate();
194
if(date < 10){
date = "0" + date;
}
var year = now.getYear();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var timeValue = " " + dow;
timeValue += " " + month + "/" + date + "/" + year;
timeValue += " " + ((hours > 12) ? hours - 12 : hours);
timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
timeValue += ((seconds < 10) ? ":0" : ":") + seconds;
timeValue += (hours >= 12) ? " P.M." : " A.M.";
document.clock.face.value = timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
// -->
</script>
</HEAD>
<BODY BGCOLOR=#000000 TEXT=#ffffff LINK=#a68c24 VLINK=#404040
onLoad="startclock()">
<FORM name="clock" onSubmit="0">
<INPUT type="text" name="face" size=29 value=" WELCOME TO IPST ! "
onClick="this.Blur()"><FORM name="clock" onSubmit="0">
</FORM>
Thanks to Netscape and the JavaScript Index (http://www.c2.org/~andreww/javascript) for this example.
Remember, if anyone has any examples of value, please email us so we may include it in the next version.
195
196