0% found this document useful (0 votes)
19 views100 pages

JavaScript Pocket Reference - Flanagan, David

The document is a JavaScript Pocket Reference by David Flanagan, published by O'Reilly & Associates in 1998. It covers various aspects of JavaScript including syntax, data types, variables, functions, and objects, providing essential information for developers. The reference is structured to assist users in understanding and utilizing JavaScript effectively in web development.

Uploaded by

MARCELO SILVA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views100 pages

JavaScript Pocket Reference - Flanagan, David

The document is a JavaScript Pocket Reference by David Flanagan, published by O'Reilly & Associates in 1998. It covers various aspects of JavaScript including syntax, data types, variables, functions, and objects, providing essential information for developers. The reference is structured to assist users in understanding and utilizing JavaScript effectively in web development.

Uploaded by

MARCELO SILVA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

Activate Your Web Pages

Pocket Reference

OREILLT David Flanagan


JavaScript
Pocket Reference
JavaScript
Pocket Reference

David Flanagan

OREILLY*
Beijing Cambridge Koln Paris Sebastopol Taipei Tokyo
JavaScript Pocket Reference
by David Flanagan

Copyright © 1998 O'Reilly & Associates, Inc. All rights reserved.


Printed in the United States of America. Published by O'Reilly &
Associates, Inc., 101 Morris Street, Sebastopol, CA 95472.

Editor: Paula Ferguson

Special Editions Editor: Gigi Estabrook

Production Editor: Paula Carroll

Production Services: Omegatype

Cover Design: Edie Freedman and Kathleen Wilson

Printing History:
October 1998: First Edition

Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly


logo are registered trademarks of O'Reilly & Associates, Inc. The
association between the image of a rhinoceros and the topic of
JavaScript pocket reference is a trademark of O'Reilly & Associates,
Inc. Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks. Where those
designations appear in this book, and O'Reilly & Associates, Inc.
was aware of a trademark claim, the designations have been
printed in caps or initial caps. While every precaution has been
taken in the preparation of this book, the publisher assumes no
responsibility for errors or omissions, or for damages resulting from
the use of the information contained herein.

@
Thisbook is printed on acid-free paper with 85% recycled content,
15% post-consumer waste. O'Reilly & Associates is committed to
using paper with the highest recycled content available consistent
with high quality.

ISBN: 1-56592-521-1 [12/98]


Table of Contents

Versions of JavaScript 1

JavaScript Syntax 1

Variables 3

Data Types 4

Expressions and Operators 9

Statements 11

Regular Expressions 16

JavaScript in HTML 17

Client-side Object Hierarchy 19

Windows and Frames 19

Forms 20

Events 21

JavaScript Security Restrictions 21

Global Properties 24

Global Functions 24

Alphabetical Object Reference 25


JavaScript
Pocket Reference

Versions ofJavaScript
The following table specifies what versions of client-side
JavaScript are supported by various versions of Netscape
Navigator and Microsoft Internet Explorer:

Version Navigator Internet Explorer

2 JavaScript 1.0

3 JavaScript 1.1 JavaScript 1.0

4 JavaScript 1.2; not JavaScript 1.2;


fully ECMA-262 EMCA-262 compliant
compliant prior to
version 4.5

JavaScript Syntax
is modeled on Java syntax, Java syntax, in
JavaScript syntax
turn, modeled on C and C++ syntax. Therefore, C, C++,
is

and Java programmers should find that JavaScript syntax is


comfortably familiar.

Case sensitivity
JavaScript is a case-sensitive language. All keywords are
in lowercase. All variables, function names, and other
identifiers must be typed with a consistent capitalization.
Whitespace
JavaScript ignores whitespace between tokens. You may
use spaces, tabs, and newlines to format and indent your
code in a readable fashion.

Semicolons
JavaScript statements are terminated by semicolons. When
a statement is followed by a newline, however, the termi-
nating semicolon may be omitted. Note that this places a
restrictionon where you may legally break lines in your
JavaScript programs: you may not break a statement
across two lines if the first line can be a complete legal
statement on its own.

Comments
JavaScript supports both C and C++ comments. Any
amount of text, on one or more lines, between /* and */
is a comment, and is ignored by JavaScript. Also, any text

between // and the end of the current line is a comment,


and is ignored. Examples:
// This is a single- line, C++- style comment.
/*
* This is a multi-line, C-style comment.
* Here is the second line.
*/
/* Another comment. */ // This too.

Identifiers
Variable, function, andlabel names are JavaScript identi-
fiers. Identifiers are composed of any number of ASCII let-
ters and and the underscore (_) and dollar sign ($)
digits,

characters. The
first character of an identifier must not be

a digit, however, and the $ character is not allowed in


identifiers in JavaScript 1.0. The following are legal
identifiers:

my_variabl e_name
vl3
$str

favaScript Pocket Reference


Keywords
The following keywords are part of the JavaScript lan-
guage, and have special meaning to the JavaScript inter-
preter. Therefore, they may not be used as identifiers:

break for this


case function true
conti nue if typeof
defaul t import var
del ete in void
do new whi 1 e
el se nul 1 with
export return
fal se switch

In addition, JavaScript reserves the following words for pos-


sible future extensions. You may not use any of these words
as identifiers either:

catch enum super


cl ass extends throw
const finally try
debugger

Variables are declared, and optionally initialized, with the


var statement:

var i ;

var j = 1+2+3;
var k, ,m,n 1 ;

var x = 3, message = 'hello world';

Variable declarations in top-level JavaScript code may be


omitted, but they are required to declare local variables
within the body of a function.

JavaScript variables are untyped: they can contain values of


any data type.

Variables
:

Global variables in JavaScript are implemented as properties


of a special global object. Local variables within functions are
implemented as properties of the Argument object for that
function.

Data Types
JavaScript supports three primitive data types: numbers,
boolean values, and strings. In addition, it supports two com-
pound data types: object and arrays. Functions are also a first

class data type in JavaScript, and JavaScript 1.2 adds support


for regular expressions (described later) as a specialized type
of object.

Numbers
Numbers in JavaScript are represented in 64-bit floating-
point format. JavaScript makes no distinction between
integers and floating-point numbers. Numeric literals

appear programs using the usual syntax: a


in JavaScript
sequence of digits, with an optional decimal point and an
optional exponent. For example:

3.14
.0001
6.02e23

Integers may also appear in octal or hexadecimal nota-


tion. An octal literal begins with 0, and a hexadecimal lit-

eral begins with x

0377 // The number 255 in octal


OxFF // The number 255 in hexadecimal

When a numeric operation overflows, it returns a special


value that represents positive or negative infinity. When
an operation underflows, it returns zero. When an opera-
tion such as taking the square root of a negative number
yields an error or meaningless result, it returns the special
value N a N which represents a value that is not-a-number.
,

Use the global function i sNaN to test for this value.


( )

JavaScript Pocket Reference


'

The Number object defines useful numeric constants. The


Math object defines various mathematical operations.

Booleans
The boolean type has two possible values, represented by
the JavaScript keywords true and fal se. These values
represent truth or falsehood, on or off, yes or no, or any-
thing else that can be represented with one bit of infor-
mation.

Strings
A JavaScript string is a sequence of arbitrary letters, digits,

and other characters. The ECMA-262 standard requires


JavaScript to support the full 1 6-bit Unicode character set.

IE 4 supports Unicode, but Navigator 4 supports only the


Latin-1 character set.

String literals appear in JavaScript programs between sin-


gle or double quotes. One style of quotes may be nested
within the other:
1

testing '

"3.14"
'name="myform"
"Wouldn't you prefer O'Reilly's book?"

When the backslash character (\) appears within a string


literal, it changes or "escapes" the meaning of the charac-
ter that follows it. The following table lists these special
escape sequences:

Escape Represents
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Tab
V Apostrophe or single quote that does
not terminate the string

Data Types
Escape Represents
\" Double-quote that does not terminate
the string
\\ Single backslash character
\ddd Character with Latin- 1 encoding speci-
fied by three octal digits ddd
\xdd Character with Latin- 1 encoding speci-
fied by two hexadecimal digits dd
\udddd Character with Unicode encoding spec-
ified by four hexadecimal digits dddd
\n n, where n is any character other than
those shown above

The String class defines many methods thatyou can use


to operate on strings. It also defines the length property,
which specifies the number of characters in a string.

The addition (+) operator concatenates strings. The equal-


ity (==) operator compares two strings to see if they con-
tain exactly the same sequences of characters. (This is

compare-by-value, not compare-by-reference, as C, C++,


or Java programmers might expect.) The inequality oper-
ator ( ! =) does the reverse. The relational operators
(< , <= , > , and >=) compare strings using alphabetical
order.

JavaScript strings are immutable, which means that there


isno way to change the contents of a string. Methods that
operate on strings typically return a modified copy of the
string.

Objects
An object is a compound num-
data type that contains any
ber of properties. Each property has a name and a value.
The . operator is used to access a named property of an
object. For example, you can read and write property val-
ues of an object o as follows:

JavaScript Pocket Reference


; ; ;

o.x = 1
o.y = 2;
o. total = o.x + o.y;

Object properties are not defined in advance as they are


in C, C++, or Java; any object can be assigned any prop-
erty. JavaScript objects are associative arrays: they associ-
ate arbitrary data values with arbitrary names. Because of
this fact, object properties can also be accessed using
array notation:

o["x"] = 1;
o["y"] = 2;

Objects are created with the new operator. You can create
a new object with no properties as follows:

var o = new Object( )

Typically, however, you use predefined constructors to


create objects that aremembers of a class of objects and
have suitable properties and methods automatically
defined. For example, you can create a Date object that
represents the current time with:

var now = new Date( )

You can also define your own object classes and corre-
sponding constructors.

In JavaScript 1.2, you can use object literal syntax to


include objects literally in a program. An object literal is a
comma-separated list of name/value pairs, contained
within curly braces. For example:

var o = {x: 1 , y :2 , total :3}

Arrays
An array is a type of object that contains numbered values
rather than named values. The [ ] operator is used to
access the numbered values of an array:

a[0] = 1;
a[l] = a[0] + a[0];

Data Types
;

The first element of a JavaScript array is element 0. Every


array has a length property that specifies the number of
elements in the array. The last element of an array is ele-
ment 1 ength-1 .

You create an array with the Array ( ) constructor:

var a = new ArrayO; // Empty array


var b = new Array(lO); // 10 elements
var c = new Array ( 1 ,2 ,3) ; // Elements 1,2,3

In JavaScript 1.2, you can use array literal syntax to


include arrays directly in a program. An array literal is a
comma-separated list of values enclosed within square
brackets. For example:

var a = [1,2,3];
var b - [1, true, [1,2], {x:l, y:2}, "Hello"];

The Array class defines a number of useful methods for


working with arrays.

Functions and methods


A is a piece of JavaScript code that is defined
function
once and can be executed multiple times by a program. A
function definition looks like this:

function sum(x, y) {

return x + y
}

Functions are invoked using the ( ) operator and passing


a list of argument values:

var total = sum(l,2); // Total is now 3

In JavaScript 1.1, you can create functions using the


FunctionO constructor:

var sum = new Functi on( "x" ,


"y", "return x+y;");

In JavaScript 1.2, you can define functions using function


literal syntax:

var sum = f uncti on(x,y ) { return x+y; }

JavaScript Pocket Reference


When a function is assigned to a property of an object, it

is called a method of that object. Within the body of the


function, the keyword this refers to the object for which
the function is a property.

Within the body of a function, the arguments!!] array


contains the complete set of arguments passed to the
function. The Function and Arguments classes represent
functions and their arguments.

null and undefined


The JavaScript keyword null is a special value that indi-
cates "no value". If a variable contains null, you know
that it does not contain a valid value of any type. There is

one other special value in JavaScript: the undefined value.


This is the value returned when you use an undeclared or
uninitialized variable or when you use a non-existent
object property. There is no JavaScript keyword for this
value.

Expressions and Operators


JavaScript expressions areformed by combining literal values
and variables with JavaScript operators. Parentheses can be
used in an expression to group subexpressions and alter the
default order of evaluation of the expression. For example:

1+2
total /n
sum(o.x, a [3])++
(l+2)*3

JavaScript defines a complete set of operators, most of which


should be familiar to all C,C++, and Java programmers. In
the following table, the P column specifies operator prece-
dence and the A column specifies operator associativity:
L means left-to-right associativity, and R means right-to-left

associativity.

Expressions and Operators


p A Operator Operation Performed
15 L • Access an object property
L [] Access an array element
L () Invoke a function
14 R ++ Unary pre- or post-increment
R Unary pre- or post-decrement
R - Unary minus (negation)
R ~ Numeric bitwise complement
R i

Unary boolean complement


R del ete Undefine a property (1.2)

R new Create a new object

R typeof Return type of operand (1.1)


R void Return undefined value (1.1)
13 L *, /, °/o Multiplication, division, modulo
12 L + ,- Addition, subtraction

L + String concatenation

11 L « Integer shift left

L » Shift right, sign extension


L >» Shift right, zero extension
10 L < 5
<= Less than, less than or equal

L > t
>= Greater than, greater than or
equal
9 L == , !
= Test for equality or inequality

L , . Test for identity or non-identity


(no type conversion)
8 L & Integer bitwise AND
A
7 L Integer bitwise XOR
6 L 1 Integer bitwise OR
5 L && Logical AND; evaluate 2nd
operand only if 1st is true
4 L 1 1 Logical OR; evaluate 2nd
operand only if 1st is fal se
?
3 R ; Conditional: if?then:else

JavaScript Pocket Reference


;

p A Operator Operation Performed


2 R Assignment
R *=, += Assignment with operation
- = , etc.

1 L > Multiple evaluation

Statements
A JavaScript program is a sequence of JavaScript statements.

Most JavaScript statements have the same syntax as the cor-


responding C, C++, and Java statements:

Expression statements
Every JavaScript expression can stand alone as a state-
ment. Assignments, method calls, increments, and decre-
ments are expression statements. For example:

s = "hel o world"1

x = Math.sqrt(4) ;

x++

Compound statements
When a sequence of JavaScript statements is enclosed
within curly braces, it counts as a single compound state-
ment. For example, the body of a whi 1 e loop consists of
a single statement. If you want the loop to execute more
than one statement, use a compound statement. This is a
common technique with if, f or , and other statements
described later.

Empty statements
The empty statement is simply a semicolon by itself. It
does nothing, and is occasionally useful for coding empty
loop bodies.

Labeled statements
In JavaScript 1.2, any statement can be labeled with a
name. Labeled loops can then be used with the labeled
versions of the break and continue statements:

]abe] : statement

Statements 11
e :

break
The break statement terminates execution of the inner-
most enclosing loop, or, in JavaScript 1.2, the named loop:
break ;

break label ; 1/ JavaScript 1.2

case
case is not a true statement. Instead it is a keyword
used to label statements within a JavaScript 1.2 switch
statement:

case constant-express/or? :

statements
[ break ] ;

Because of the nature of the switch statement, a group


of statements labeled by case should usually end with a
break statement.

continue
The continue statement restarts the innermost enclosing
loop, or, in JavaScript 1.2, restarts the named loop:

continue ;

continue label ; //JavaScript 1.2


de, aul t
Like case, default is not a true statement, but instead a
label that may appear within a JavaScript 1.2 swi tch
statement:

defaul t
statements
[ break ] ;

ao/whi 1

The do/whi 1 e loop repeatedly executes a statement


while an expression is true . It is like the whi 1 e loop,
except that the loop condition appears (and is tested) at
the bottom of the loop. This means that the body of the
loop will be executed at least once:

12 JavaScript Pocket Reference


do
statement
while expression
( ) ;

This statement is new in JavaScript 1.2. In Navigator 4, the


continue statement does not work correctly within do/
whi 1 e loops.

export
The export statement was introduced in Navigator 4. It
makes the specified functions and properties accessible to
other windows or execution contexts:

export expression [, expression .. . ];

for
The for statement is an easy-to-use loop that combines
the initialization and increment expressions with the loop
condition expression:

for {initialize ; test ; increment)


statement

The for loop repeatedly executes a statement as long as


its test expression is true. It evaluates the initialization
expression once before starting the loop and evaluates
the increment expression at the end of each iteration.

for/i n

The f or/i n statement loops through the properties of a


specified object:

for {variable in object)


statement

The f or/i n loop executes a statement once for each


property of an object. Each time through the loop, it

assigns the name of the current property to the specified


variable. Some properties of pre-defined JavaScript
objects are not enumerated by the f or/i n loop. User-
defined properties are always enumerated.

function
The function statement defines a function in a JavaScript
program:

Statements 13
4

function funcname(args) {

statements
>

This statement defines a function named funcname, with


a body that consists of the specified statement, and argu-
ments as specified by args args is a comma-separated
.

list of zero or more argument names. These arguments

can be used in the body of the function to refer to the


parameter values passed to the function.

if/el se
The i f statement executes a statement if an expression is

true:

if ( expression )

statement

When an else clause is added, the statement executes a


different statement if the expression is f al se :

if ( expression )

statement
el se
statementZ

Any else clause may be combined with a nested i f/e 1 se

statement to produce an el se if statement:

if expression
( )

statement
else if expression2
( )

statementZ
el se
statements
import
The import statement was introduced in Navigator 4
along with export It makes the named functions and
.

variables available in the current window or execution


second form of the statement, makes all
context, or, in the
properties and methods of the specified object available
within the current context:

1 JavaScript Pocket Reference


:

import expression [, expression];


import expression .* ;

return
The return statement causes the currently executing
function to stop executing and return to its caller. If fol-
lowed by an expression, the value of that expression is
used as the function return value.

return ;

return expression ;

switch
The switch statement is a multi-way branch. It evaluates
an expression and then jumps to a statement that is
labeled with a case clause that matches the value of the
expression.If no matching case label is found, the

switch statement jumps to the statement, if any, labeled


with defaul t

switch expression { ( )

case constant-expression statements :

[ case constant-expression statements : ]

[ . . . ]

defaul t : statements
}

var
The var statement declares and optionally initializes one
or more variables. Variable declaration is optional in top-
level code, but is required to declare local variables within
function bodies:

var name [ = value ] [ , nameZ [ = value2 ]...];


whi 1 e
The whi 1 e statement is a basic loop. It repeatedly exe-
cutes a statement while an expression is true:

while expression ( )

statement ;
with
The with statement adds an object to the scope chain, so
that a statement is interpreted in the context of the object:

Statements 15
with ( object )

statement ;

The use of wi th statements is discouraged.

Regular Expressions
JavaScript 1.2 supports regular expressions, using the same
syntax as Perl 4. A regular expression is specified literally as
a sequence of characters within forward slashes (/), or as a
JavaScript string passed to the RegExpO constructor. The
optional g (global search) and i (case-insensitive search)
modifiers may follow the second / character, or may be
passed to RegExpO.

The following table summarizes regular expression syntax:

Character Meaning
\n, \r,\t Match literal newline, carriage return, tab
w, \/, v*, Match a special character literally, ignoring
\H -, \?, etc. or escaping its special meaning

[. . .] Match any one character between brackets


A
[ . .] Match any one character not between
brackets

Match any character other than newline


\w, \W Match any word/non-word character
\s, \S Match any whitespace/non-whitespace
\d, \D Match any digit/non-digit
A
$ Require match at beginning/end of a
string, or in multi-line mode, beginning/
end of a line

\b, \B Require match at a word boundary


non-boundary
?
Optional term; Match zero or one time
+ Match previous term one or more times
*
Match term zero or more times

16 JavaScript Pocket Reference


Character Meaning
in} Match previous term exactly n times

{n,} Match previous term n or more times


{n,m} Match at least n but no more than m times
a I
b Match either a or b

(sub) Group sub-expression sub into a single


term, and remember the text that it

matched
\n Match exactly the same characters that
were matched by sub-expression number
n

%n In replacement strings, substitute the text


that matched the nth sub-expression

JavaScript in HTML
Client-side JavaScript code may be embedded in HTML files

in several ways:

<SCRIPT> tag
Most JavaScript code appears in HTML files between a
<SCRIPT> tag and a </SCRIPT> tag. The <SCRIPT> tag
can also be used to include an external file of JavaScript
code into an HTML document. The <SCRI PT> tag sup-
ports a number of attributes, including these three impor-
tant ones:

LANGUAGE
Specifies the scripting language in which the script is
written. In most browsers, this attribute defaults to
"JavaScript". You must set it if you are mixing
scripting languages, such as JavaScript and VBScript.

Set this attribute to "JavaScript 1.1" to specify that


the code uses JavaScript 1.1 features, and that it should
not be interpreted by JavaScript 1.0 browsers. Set this

attribute to "JavaScript 1.2" to specify that only Java


Script 1.2 browsers should interpret the code. (Note,

JavaScript in HTML 17
however, that Navigator 4 has some non-standard
behaviors when "JavaScript 1.2" is specified.)

SRC
Specifies the URL of an external script to be loaded and
executed. Files of JavaScript code typically have a js
extension. Note that the </SCRI PT> tag is still required
when this attribute is used. Supported in JavaScript 1.1
and later.

ARCHIVE
Specifies the URL of a JAR file that contains the script
specified by the SRC attribute. Supported in JavaScript
1.2 and later. Archives are required to use Navigator 4
signed scripts.

Event handlers
JavaScript code may also appear as the value of event
handler attributes of HTML tags. Event handler attributes
always begin with "on". The code specified by one of
these attributes is executed when the named event occurs.
For example, the following HTML specifies a button that
displays a dialog box when clicked:

<INPUT TYPE=button VALUE="Press Me"


worl d! ">
;
on CI ick="al ert( ' hel 1 o '
)

JavaScript URLs
JavaScript code may appear in a URL that uses the special
javascript: pseudo-protocol. The JavaScript code is
evaluated, and the resulting value (converted to a string,
if necessary) is used as the contents of the URL. Use the

void operator if you want a JavaScript URL that executes


JavaScript statements without overwriting the current
document:

<F0RM ACTION="javascript:void val idate( ) ">

JavaScript entities
In JavaScript 1.1, HTML attribute values may contain Jav-
aScript code in the form of JavaScript entities. An HTML
entity is a string like & 1 1 ; that represents some other char-

ts JavaScript Pocket Reference


J ] ]3

acter or string. A JavaScript entity is JavaScript code con-


tained within & { and } ; . Its value is the value of the
JavaScript expression within:
n
<B0DY BGCOLOR= &{getFavoriteColor()}; M >

Client-Side Object Hierarchy


Client-side JavaScript has access to a suite of client-side
objects that represent the browser, browser windows and
frames, HTML documents, and elements within HTML docu-
ments. These objects are structured in a hierarchy as shown
in Figure 1.

self, window,
parent, top \
CB>
pluffinan
wtovsWmdo* objects ]

array of Plugm objects

navigator
Navigator object * mimeTypes
way of MimeType objects
[]

frames [
array of Window objects forms [] elements []

may of Form objects


location
h array of HIMi Form
element objects:

Button
Location object anchors [
Checkbox
may of Anchor objects FUeUphad «H>
history Hidden
Password
Historyobjed links [}
Radio
may of Link objects itset options!]
Select
orrayof
€S> !

Document object
t images [
array of (mage objects
Submit
hxt
Jextarea
Optmohjects j

<B>
applets []
array of applets

<S>
embedsH
array of embedded objects

Figure 1. The client-side object hierarchy

Client-Side Object Hierarchy 19


Windows and Frames
The Window object represents a browser window or frame
in client-side JavaScript. Each Window object has properties
that refer to its nested frames, if any, and its containing win-
dow or frame, if any. Figure 2 illustrates these properties.

Figure 2. Windows and frames

Forms
One of the powerful features of JavaScript is its ability to

manipulate HTML forms. HTML defines the following form


elements:

20 JavaScript Pocket Reference


Button (<INPUT TYPE=button>)
A graphical push button; on CI i ck events

Checkbox (<IHPUJ TYPE=checkbox>)


A toggle button without mutually-exclusive behavior;
onCl i ck events

FileUpload (<INPUT TYPE=file>)


A file entry field and file browser; onChange events

Hidden (<I HP i)T TYPE=hidden>)


A non-visual data field; no event handlers
Option (<0PTI0N>)
An item within a Select list; event handlers are on the
Select object, not Option objects

Password (<INPUT TYPE=password>)


An input field for sensitive data; onChange events
Radio (<WPUT TYPE=radio>)
A toggle button with mutually-exclusive "radio" behavior;
onCl i ck events

Reset (<IttPUT TYPE=reset>)


A button that resets a form; on CI i ck events

Sefeef(<SELECT[MULTIPLE]>. .</SELECT>) .

A list or drop-down menu from which one or more


Option items may be selected; onChange events

Submit (<IHPUT TYPE=submi t>)


A button that submits a form; onC 1 i c k events

Text (<INPUT TYPE=text>)


A single-line text entry field; onChange events

TextArea (<TEXTAREA>. . . </TEXTAREA>)


A multi-line text entry fields; onChange events

Figure 3 shows a web page that contains each type of form


element.

Forms 21
,

file E<& ¥>ew So Favorites

Refresh Home Search


S
F»/Offte$ Hittoiy Channels
s
Fullscreen
ta

Ad*ass|«JE avosc

Links «yBastcrffrsV» gjChanftftt Guide «JQj«c srNewfi gjintemet Start

Input Events[3]
Username: Password:
Change: browser (other)
[l]|david [2]h~- :: browser (other)
Focus hobbies
: ( )

Click: hobbies (

Filename: [4]| programming )

Change: hobbies (

programming )

My Computer Peripherals: My Web Browser: Click: hobbies caffeine (

[5](7 28.8KModem [6] c Netscape Navigator Change: hobbies caffeine (

[5] f? Printer [6] r Internet Explorer Click: hobbies (

[5] r Tape Backup [6] * Other programming caffeine )

Change: hobbies (

programming caffeine )

:: hobbies programmii (

caffeine )

My Favorite Col or: Focus: color red ( )

Click: color red ( )

Click: color blue ( )

Change: color blue ( )

Fonn Elements [1] Text [2] Password [3] Textarea [4} FileUpload [5] Checkbox !;

[6] Radio [7] Select (list) [8] Select (menu) [9] Button [10] Submit [11] Reset

£3 Dona Jii My Computer

Figure 3- Form elements

Events
Client-side JavaScript supports a number of event types. The
following table lists the event handlers and the client-side
objects that support the handlers. Note that some events, such
as onDbl CI i ck , are not reliably generated on all platforms.

Event Handler Supported By


onAbort Image (JavaScript 1.1)
onBl ur Text elements; Window and all other form
onFocus elements (1.1)
onChange Select, text input elements
onCl i ck Button elements, Link. Return fal se to
cancel default action.
onDblClick Document, Link, Image, Button elements
(1.2)
onError Image, Window (1.1)

22 JavaScript Pocket Reference


t , , .

Event Handler Supported By


onKeyDown Document, Image, Link, text elements
onKeyPress , (1.2). Return fal se to cancel.
onKeyUp
onLoad , Window; Image in 1.1
onUnl oad
onMouseDown Document, Link, Image, Button elements
onMouseUp (1.2). Return fal se to cancel.
onMouseOver Link; Image and Layer (1.2). Return t rue to
onMouseOut prevent URL display.

onReset, Form (1.1). Return f al se to prevent reset


onSubmi or submission.

JavaScript
Security Restrictions
For security reasons, there are restrictions on the tasks that
untrusted JavaScript code can perform. In Navigator 4, signed
scripts can circumvent these restrictions by requesting certain
privileges:

Same origin policy


Scriptscan only read properties of windows and docu-
ments that were loaded from the same web server unless
they have Uni versal BrowserRead.

User's browsing history


Scripts cannot read the array of URLs from the History
object without Uni versal BrowserRead.

File uploads
Scriptscannot set the value property of the FileUpload
form element without Universal BrowserRead.

Sending email and posting news


Scripts cannot submit forms to a ma i to or news 1 : : URL
without user confirmation or Uni versal SendMai 1

JavaScript Security Restrictions 23


Closing windows
A script can only close browser windows that it

created, unless it gets user confirmation or has


Uni versa 1 BrowserWri te.

Snooping in the cache


A script cannot load any about URLs, such as :

about:cache, without Uni versa Browser Read. 1

Hidden windows and window decorations


A script cannot create small or offscreen windows or win-
dows without a and cannot show or hide window
titlebar,

decorations without Universal BrowserWri te.

Intercepting or spoofing events


A script cannot capture events from windows or docu-
ments from a different server and cannot set the fields of
an Event object without Uni versal BrowserWri te.

Reading and setting preferences


A script cannot read or write user preferences using
Navigator.preferenceO without
Uni versal Preferences Read or
Universal PreferencesWri te.

Global Properties
Core JavaScript defines two global constants:
Infinity
A numeric constant that represents infinity. Internet
Explorer 4; ECMA-262; not supported by Navigator 4.

NaN
The not-a-number constant. Internet Explorer 4; ECMA-
262; not supported by Navigator 4.

In addition to these core global properties, the Window


object defines a number of client-side global properties.

24 JavaScript Pocket Reference


Global Functions
Core JavaScript defines a handful of global functions:
escape(s)
Encode a string for transmission. JavaScript 1.0;
ECMA-262; Unicode support in Internet Explorer 4.

eval {code)
Execute JavaScript code from a string.

getCl dss(javdobj)
Return the JavaClass of a JavaObject. Navigator 3.

i sFini te(n)
Determine whether a number is finite. JavaScript 1.2;

ECMA-262.
isNaN(x)
Check for not-a-number. JavaScript 1.1; ECMA-262.
parseFl oat(s)
Convert a string to a number. JavaScript 1.0; enhanced in
JavaScript 1.1; ECMA-262.

parselnt(s, radix)
Convert a string to an integer. JavaScript 1.0; enhanced in
JavaScript 1.1; ECMA-262.
unescape(s)
Decode an escaped string. JavaScript 1.0; ECMA-262;
Unicode support in Internet Explorer 4.

In addition to these core global functions, the Window object


defines a number of client-side global methods.

Global Functions 25
1

Anchor

Alphabetical Object Reference

Anchor the target of a hypertext link

Availability

Client-side JavaScript 1.2

Inherits From
HTMLElement

Synopsis

document. anchors[/]
document, anchors. length

Properties

Anchor inherits properties from HTMLElement and also


defines or overrides the following:

name
The name of an anchor.
text
The text of an anchor. Navigator 4.

x
The X-coordinate of an anchor. Navigator 4.

y
The Y-coordinate of an anchor. Navigator 4.

Applet an applet embedded in a web page

Availability

Client-side JavaScript 1 .

26 JavaScript Pocket Reference


]

Arguments

Synopsis

document, appl ets[/


document. appletName

Properties

The properties of an Applet object are the same as the public


fields of the Java applet it represents.

Methods
The methods of an Applet object are the same as the public
methods of the Java applet it represents.

Area see Link

Arguments
arguments and other properties of a function

Availability

Core JavaScript 1.1; ECMA-262; only defined within a func-


tion body

Synopsis

arguments

Properties

cal 1 ee
The function that is currently running. JavaScript 1.2;

ECMA-262.
cal ler
The calling context. Navigator 4.

1 ength
The number of arguments passed to a function.

Alphabetical Object Reference 27


)

Array

Array built-in support for arrays

Availability

Core JavaScript 1.1; enhanced by ECMA-262; enhanced in


Navigator 4. Array functionality is available in JavaScript 1.0,
but the Array object itself is not supported by Navigator 2.

Constructor

new Array( )

new Array(s7'ze)
new Array(e7 ementO, elementl, . . . , elementn)

Properties

1 ength
The size of an array. JavaScript 1.1, Internet Explorer 3;
ECMA-262.

Methods
concat( va ue, 1 . . . )

Concatenate arrays. JavaScript 1.2.

join(separator)
Concatenate array elements to form a string. JavaScript

1.1; ECMA-262.

pop(
Remove and return the last element of an array. Navigator
4.

push( va ue 1 , . . . )

Append elements to an array. Navigator 4.

reverse( )

Reverse the elements of an array. JavaScript 1.1; ECMA-


262.

shiftO
Shift array elements down. Navigator 4.

28 JavaScript Pocket Reference


i 1

Button

si iceistart, end)
Return a portion of an array. JavaScript 1.2.

sort(orderfunc)
Sort the elements of an array. JavaScript 1.1; ECMA-262.
spl ceistart, del eteCount value, , . . . )

Insert, remove, or replace array elements. Navigator 4.

toString( )

Convert an array to a string. JavaScript 1.1; ECMA-262.

unshi ft( va ue, 1 . . . )

Insert elements at the beginning of an array. Navigator 4.

Boolean support for boolean values

Availability

Core JavaScript 1.1; ECMA-262

Constructor

II Constructor function
new Bool ean( va ue)
II Conversion function
Bool ean( va ue) 1

Methods
toString( )

Convert a boolean value to a string.

Button a graphical pushbutton

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Alphabetical Object Reference 29


]

Checkbox

Synopsis

form, name
form, el ements[/]

Properties

Button inherits properties from Input and HTMLElement and


also defines or overrides the following:

val ue
The text that appears in a Button.

Methods
Button inherits methods from Input and HTMLElement.

Event Handlers
Button inherits event handlers from Input and HTMLElement
and also defines or overrides the following:
oncl i ck
The handler invoked when a Button is clicked.

Checkbox a graphical checkbox

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Synopsis

II A single checkbox with a unique name


form. name
form. el ements[ /
// A group of checkboxes with the same name
form.nameli]

30 JavaScript Pocket Reference


Crypto

Properties

Checkbox inherits properties from Input and HTMLElement


and also defines or overrides the following:
checked
Whether a Checkbox is checked.

defaul tChecked
The initial state of a Checkbox.

val ue
The value returned when a form is submitted.

Methods
Checkbox inherits the methods of Input and HTMLElement.

Event Handlers
Checkbox inherits event handlers from Input and HTMLEle-
ment and also defines or overrides the following:
oncl ick
The handler invoked when a Checkbox is selected.

Crypto cryptography-related resources

Availability

Client-side Navigator 4.04 and later

Synopsis

crypto

Functions
crypto. random (numbytes)
Generate random byte strings.

crypto. signText( text, CASelection, allowedCA. . . )

Ask the user to digitally sign text.

Alphabetical Object Reference 31


i ) ;

Date

Date manipulate dates and times

Availability

Core JavaScript 1.0; enhanced by ECMA-262

Constructor

new Date( )
new Date (077 iseconds) 7 7

new Ddte(ddtestring) ;

new Date(year, month, day, hours, minutes,


seconds, ms)

Methods
Note that unlike most JavaScript objects, the Date object has
no properties can be read and written directly; instead,
that
all access to date and time fields is done through methods:

getDateO
Return the day of the month. JavaScript 1.0; ECMA-262.

getDayO
Return the day of the week. JavaScript 1.0; ECMA-262.

getFullYearO
Return the year (local time). JavaScript 1.2; ECMA-262.

getHours( )

Return the hours field of a Date. JavaScript 1.0; ECMA-262.

getMi 1 1 seconds( )

Return the milliseconds field of a Date (local time).


JavaScript 1.2; ECMA-262.

getMinutes( )

Return the minutes field of a Date. JavaScript 1.0; ECMA-


262.

getMonth(
Return the month of a Date. JavaScript 1.0; ECMA-262.

32 JavaScript Pocket Reference


) ) )

Date

getSeconds(
Return the seconds field of a Date. JavaScript 1.0;

ECMA-262.
getTime( )

Return a Date in milliseconds. JavaScript 1.0; ECMA-262.


getTimezoneOffset(
Determine the offset from GMT. JavaScript 1.0; ECMA-262.
getUTCDateO
Return the day of the month (universal time). JavaScript
1.2; ECMA-262.

getUTCDayO
Return the day of the week (universal time). JavaScript
1.2; ECMA-262.

getUTCFullYearO
Return the year (universal time). JavaScript 1.2; ECMA-
262.

getUTCHoursO
Return the hours field of a Date (universal time).
JavaScript 1.2; ECMA-262.
getUTCMil 1 iseconds( )

Return the milliseconds field of a Date (universal time).


JavaScript 1.2; ECMA-262.

getUTCMinutesO
Return the minutes field of a Date (universal time).
JavaScript 1.2; ECMA-262.

getUTCMonthO
Return the month of the year (universal time). JavaScript
1.2; ECMA-262.
getUTCSeconds(
Return the seconds field of a Date (universal time).
JavaScript 1.2; ECMA-262.

Alphabetical Object Reference 33


Date

getYear( )

Return the year field of a Date. JavaScript 1.0; ECMA-262;


deprecated in JavaScript 1.2 in favor ofgetFullYearO.
set Date (day_of_month)
Set the day of the month. JavaScript 1.0; ECMA-262.
setFul 1 Year(year)
Set the year (local time). JavaScript 1.2; ECMA-262.

setHours(/?OL/rs)
Set the hours field of a Date. JavaScript 1.0; ECMA-262.

setMi 1 1 i seconds (/777 7 7 is)


Set the milliseconds field of a Date (local time). JavaScript
1.2; ECMA-262.

setMinutes(/777/7wtes)
Set the minutes field of a Date. JavaScript 1.0; ECMA-262.
setMonth(tf70/7t/?)
Set the month field of a Date. JavaScript 1.0; ECMA-262.

setSeconds(seco/7c/s)
Set the seconds field of a Date. JavaScript 1.0; ECMA-262.
setTime(/777 7 7 i seconds)
Set a Date in milliseconds. JavaScript 1.0; ECMA-262.

setUTCDate (day__of_month)
Set the day of the month (universal time). JavaScript 1.2;
ECMA-262.
setUTCFul 1 Year (year)
Set the year (universal time). JavaScript 1.2; ECMA-262.

setUTCHours(/70i/rs)
Set the hours field of a Date (universal time). JavaScript
1.2; ECMA-262.
setUTCMi 1 1 i seconds (/7? / 7 7 is)
Set the milliseconds field of a Date (universal time).
JavaScript 1.2; ECMA-262.

setUTCMi nutes(/W7/7wtes)
Set the minutes field of a Date (universal time). JavaScript
1.2; ECMA-262.

34 JavaScript Pocket Reference

J
Date

setUTCMonth(/770/7t/7)
Set the month (universal time). JavaScript 1.2; ECMA-262.
setUTCSeconds( seconds)
Set the seconds field of a Date (universal time). JavaScript
1.2; ECMA-262.

setYear(year)
Set the year field of a Date. JavaScript 1.0; ECMA-262; dep-
recated in JavaScript 1.2 in favor ofsetFullYearO.
toGMTStringO
Convert a date to a universal time string. JavaScript 1.0;

ECMA-262; deprecated in JavaScript 1.2 in favor of


toUTCStringO.
toLocal eString( )

Convert a Date to a string. JavaScript 1.0; ECMA-262.


toString( )

Convert a date to a string. JavaScript 1.0; ECMA-262.

toUTCStringO
Convert a date to a string (universal time). JavaScript 1.2;

ECMA-262.

valueOfO
Convert a date to a number. JavaScript 1.1; ECMA-262.

Static Methods
Date.parse(c/ate)
Parse a date/time string. JavaScript 1.0; ECMA-262.

Date.UTC(year, month, day, hours, minutes,


seconds, ms)
Convert a date specification to milliseconds. JavaScript
1.0; ECMA-262.

Alphabetical Object Reference 35


Document

Document represents an HTML document

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1 and in


Navigator 4 and Internet Explorer 4

Inherits From
HTMLElement

Synopsis

window, document
document

Properties

Document inherits properties from HTMLElement and also


defines numerous properties. Navigator 4 and Internet
Explorer 4 both define a number of incompatible Document
properties, used mostly for DHTML; they are listed separately
after the generic properties:

al inkCol or
The color of activated links.

anchors[]
The Anchors in a document. JavaScript 1.0; array elements
are null prior to JavaScript 1.2.

appl ets[]
The applets in a document. JavaScript 1.1.

bgCol or
The document background color.

cookie
The cookie(s) of the document.
domain
The security domain of a document. JavaScript 1.1.

embeds[]
The objects embedded in a document. JavaScript 1.1.

36 JavaScript Pocket Reference


Document
fgCol or
The default text color.

forms[]
The Forms in a document.

images[]
The images embedded in a document. JavaScript 1.1.

1 astModif ied
The modification date of a document.

1 inkCol or
The color of unfollowed links.

links[]
The Link objects in a document.

1 ocation
The URL of the current document. JavaScript 1.0; depre-
cated in JavaScript 1.1 in favor of Document URL. .

plugins[]
The objects embedded in a document. JavaScript 1.1.

referrer
The URL of the linked-from document. JavaScript 1.0;

non-functional in Internet Explorer 3.

title
The title of a document.

URL
The URL of the current document. JavaScript 1.1.

vl inkCol or
The color of visited links.

Navigator 4 Properties
cl asses
Define style classes.

height
The height of a document.

Alphabetical Object Reference 37


)

Document

ids
Define styles for individual tags.

layers[]
The layers contained in a document.

tags
Define styles for HTML tags.

width
The width of a document.

Internet Explorer 4 Properties

acti veEl ement


Which input element has the focus.

all[]
All HTML elements in a document.

charset
The character set in use.

chi ldren[]
The child elements of the document.

defaul tCharset
The default character set of a document.

expando
Disallow new property creation.

parentWindow
The window of a document.

readyState
The loading status of a document.

Methods
Document inherits methods from HTMLElement and also
defines some methods. Navigator 4 and IE 4 both define a
number of incompatible Document methods, used mostly for
DHTML; they are listed separately after the generic methods:
cl ear(
Clear a document. JavaScript 1.0; deprecated.

38 JavaScript Pocket Reference


) ) )

Document
cl ose(
Close an output stream.

oper\(mimetype)
Begin a new document.

wri te( va 1 ue, . . . )

Append data to a document.

writel n( va ue,1 . . .

Append data and a newline to a document.

Navigator 4 Methods
captureEvents( event mask)
Specify event types to be captured.

contextual (stylel, style2, . . . )

Define a contextual style.

getSel ection(
Return the selected text.

rel easeEvents(ei/e/7t/7?as^)
Stop capturing events.

routeEvent(ei/er?t)
Pass a captured event to the next handler.

Internet Explorer 4 Methods

el ementFromPoi nt(x, y)
Determine which HTML element is at a given point.

Event Handlers
The <B0DY> tag has onLoad and onLlnl oad attributes. Tech-
however, the onload and onunl oad event handlers
nically,
belong to the Window object, rather than the Document
object.

Alphabetical Object Reference 39


Event
I
Event details about an event

Availability

Client-side JavaScript; incompatible versions are supported


by Navigator 4 and Internet Explorer 4

Synopsis

1/ Event handler argument in Navigator 4


function handler (event) {...}
// Window property in IE 4
window, event

Navigator 4 Properties
data
Data from a DragDrop event. Requires Universal -

BrowserWrite privilege to set; requires Universal -

BrowserRead privilege to read.


height
The new height of a resized window or frame.

1 ayerX
The X-coordinate, within a layer, of the event.

1 ayerY
The Y-coordinate, within a layer, of the event.

modi f iers
Which modifiers keys are held down.

pageX
The X-coordinate, within a page, of the event.

pageY
The Y-coordinate, within a page, of the event.

screenX
The screen X-coordinate of the event. JavaScript 1.2.

screenY
The screen Y-coordinate of the event. JavaScript 1.2.

40 JavaScript Pocket Reference


e

Event

target
The object on which the event occurred.

type
The type of the event. JavaScript 1.2.

TYPE
Static event type constants for bitmasks.

which
Which key or mouse button was clicked.

width
The new width of a resized window or frame.

x
The X-coordinate of the event within a positioned ele-
ment. JavaScript 1.2.

y
The Y-coordinate of the event within a positioned ele-
ment. JavaScript 1.2.

Internet Explorer 4 Properties

altKey
Whether the ALT key was pressed during an event.
button
Which mouse button was pressed.

cancel Bubbl
Stop event propagation.

cl ientX
The X-coordinate, within a page, of the event.

cl ientY
The Y-coordinate, within a page, of the event.

Ctrl Key
Whether the CTRL key was pressed during an event.

f romEl ement
The object the mouse is moving from.
keyCode
The Unicode encoding of the key typed.

Alphabetical Object Reference 41


FileUpload

offsetX
The X-coordinate of the event, relative to the container.

offsetY
The Y-coordinate of the event, relative to the container.

reason
Data transfer status.

returnVal ue
Specify a return value for the event handler.

screenX
The screen X-coordinate of the event. JavaScript 1.2.

screenY
The screen Y-coordinate of the event. JavaScript 1.2.

shiftKey
Whether the SHIFT key was pressed during an event.
srcEl ement
The object on which the event occurred.
srcFi 1 ter
The filter that changed.

toEl ement
The object to which the mouse is moving.

type
The type of the event. JavaScript 1.2.

x
The X-coordinate of the event within a positioned ele-
ment. JavaScript 1.2.

y
The Y-coordinate of the event within a positioned ele-
ment. JavaScript 1.2.

FileUpload a file upload field for form input

Availability

Client-side JavaScript 1.0

42 JavaScript Pocket Reference


Form

Inherits From
Input, HTMLElement

Synopsis

form, name
form, el ements[ /]

Properties

FileUpload inherits properties from Input and HTMLElement


and defines or overrides the following:
val ue
The filename selected by the user. JavaScript 1.1.

Methods
FileUpload inherits methods from Input and HTMLElement.

Event Handlers
FileUpload inherits event handlers from Input and HTMLEle-
ment and defines or overrides the following:

onchange
The handler invoked when input value changes.

Form an HTML input form

Availability

Client-side JavaScript 1.0

Inherits From
HTMLElement

Synopsis

document. form_name
document. forn\s[form_number]

Alphabetical Object Reference 43


)

Form

Properties

Form inherits properties from HTMLElement and also defines


or overrides the following:

acti on
The URL for form submission. JavaScript 1.0; read-only in
Internet Explorer 3-

el ements[]
The input elements of the form.

el ements. ength 1

The number of elements in a form.

encodi ng
The encoding of form data. JavaScript 1.0; read-only in
Internet Explorer 3-

1 ength
The number of elements in a form.

method
The submission method for the form. JavaScript 1.0; read-
only in Internet Explorer 3.

name
The name of a form.

target
The window for form results. JavaScript 1.0; read-only in
Internet Explorer 3-

Methods
Form inherits methods from HTMLElement and also defines
the following:

reset( )

Reset the elements of a form. JavaScript 1.1.

submi t(
Submit a form.

44 JavaScript Pocket Reference


t ]

Function

Event Handlers
Form inherits event handlers from HTMLElement and also
defines the following:

onreset
The handler invoked when a form is reset. JavaScript 1.1.

onsubmi
Invoked when a form is submitted.

Frame a type of Window object; see Window

Availability

Client-side JavaScript 1.0

Synopsis

window, f rames[/
window, frames.length
f rames[ 7]
frames .ength
1

Function a JavaScript function

Availability

Core JavaScript 1.0; enhanced in JavaScript 1.1 and 1.2

Synopsis

II Function definition statement


function functionname(argument_name_l ist)
I

body
}

// Unnamed function literal; JavaScript 1.2


function (argument_name_l i st { body} )

II Function invocation
functionnamei argument _va ue_l ist) 1

Alphabetical Object Reference 45


Hidden

Constructor

// JavaScript 1.1 and later


new V[\x\ct\on{argument_names , body)

Properties

arguments!!]
Arguments passed to a function. JavaScript 1.0; ECMA-
262; deprecated in favor of the Arguments object.

arity
The number of declared arguments. Navigator 4, with
LANGUAGE="JavaScriptl.2".
cal 1 er
The function that called this one.

1 ength
The number of declared arguments. JavaScript 1.1;
ECMA-262.
prototype
The prototype for a class of objects. JavaScript 1.1.

Methods
apply( thisobj args) ,

Invoke a function as a method of an object. Navigator 4.

toString( )

Convert a function to a string. JavaScript 1.0; ECMA-262.

Hidden hidden data for client/server communication

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

46 JavaScript Pocket Reference


]

History

Synopsis

form, name
form, el ements[7

Properties

Hidden inherits properties from Input and HTMLElement and


defines or overrides the following:

val ue
Arbitrary data submitted with a form.

History the URL history of the browser

Availability

Client-side JavaScript 1.0; additional features available in


Navigator 4 with the Universal BrowserRead privilege

Synopsis

window, history
frame, hi story
hi story

Properties

current
The URL of the currently displayed document. Navigator
4; requires Uni versal BrowserRead.

length
The number of elements in the history array. Navigator 2,
Internet Explorer 4.

next
The URL of the next document in the history array. Navi-
gator 4; requires Uni versal BrowserRead.

previous
The URL of the previous document in the history array.

Navigator 4; requires Uni versal BrowserRead.

Alphabetical Object Reference 47


( 1 .

HTMLElement
I Methods
backO
Return to the previous URL. JavaScript 1.0.

forward( )

Visit the next URL. JavaScript 1.0.

go re 7 a t i ve_pos i tion, targe t_string)


Revisit a URL. JavaScript 1.0; enhanced in JavaScript 1.1.

toString( )

Return browsing history, formatted in HTML. Navigator 4;


requires Uni versal BrowserRead.

HTMLElement the superclass of all HTML elements

Availability

Client-side JavaScript 1.2

Internet Explorer 4 Properties

all[]
All elements contained within an element.

chi dren[]
The direct children of an element.

cl assName
The value of the CLASS attribute.

document
The Document object that contains an element.

id
The value of the I D attribute.

innerHTML
The HTML text contained within the element.

innerText
The text within the element.

1 ang
The value of the LANG attribute.

48 JavaScript Pocket Reference


HTMLElement
offsetHeight
The height of the element.
offsetLeft
The X-coordinate of the element.
off setParent
Defines the coordinate system of the element.

offsetTop
The Y-coordinate of the element.
offsetWidth
The width of the element.
outerHTML
The HTML of an element.
outerText
The text of an element.
parentEl ement
The container of an element.
sourcelndex
The index of the element in Document . al 1 [].

style
The inline CSS style of the element.

tagName
The tag type of an element.

title
Tool tip for an element.

Navigator 4 Methods
handl eEvent(ei/e/7t)
Pass an event to an appropriate handler.

Internet Explorer 4 Methods

contains( target)
Whether one element is contained in another.

getAttributeCftame)
Get an attribute value.

Alphabetical Object Reference 49


HTMLElement

insertAdjacentHTML(w/7ere, text)
Insert HTML text before or after an element.

insertAdjacentText(iv/?ere, text)
Insert plain text before or after an element.

removeAttribute(/7<3tf?e)
Delete an attribute.

scrol 1 IntoView( top)


Make an element visible.

setAttribute(/7d/ne, value)
Set the value of an attribute.

Event Handlers
oncl ick
The handler invoked when the user clicks on an element.
JavaScript 1.2; HTML 4.0.

ondbl cl ick
The handler invoked when the user double-clicks on an
element. JavaScript 1.2; HTML 4.0.

onhel p
The handler invoked when the user presses Fl. Internet
Explorer 4.

onkeydown
The handler invoked when the user presses a key. Java-
Script 1.2; HTML 4.0.

onkeypress
The handler invoked when the user presses a key. Java-
Script 1.2; HTML 4.0.

onkeyup
The handler invoked when the user releases a key. Java-
Script 1.2; HTML 4.0.

onmousedown
The handler invoked when the user presses a mouse but-
ton. JavaScript 1.2; HTML 4.0.

50 JavaScript Pocket Reference


i

Image

onmousemove
The handler invoked when mouse moves within an ele-
ment. JavaScript 1.2; HTML 4.0.

onmouseout
The handler invoked when mouse moves out of an ele-
ment. JavaScript 1.2; HTML 4.0.

onmouseover
The handler invoked when mouse moves over an ele-
ment. JavaScript 1.2; HTML 4.0.

onmouseup
The handler invoked when the user releases a mouse but-
ton. JavaScript 1.2; HTML 4.0.

Image an image embedded in an HTML document

Availability

Client-side JavaScript 1.1

Inherits From
HTMLElement

Synopsis

document. images[ /]
document, images.length
document, image-name

Constructor

new Image(iv/cft/7, height)

Properties

Image inherits properties from HTMLElement and defines or


overrides the following:

border
The border width of an image.

Alphabetical Object Reference 51


Input

compl ete
Whether an image load is complete.

height
The height of an image.
hspace
The horizontal padding for an image.

1 owsrc
An alternate image for low-resolution displays.

name
The name of an image.
src
The URL of the embedded image.
vspace
The vertical padding for an image.
width
The width of an image.

Event Handlers
Image inherits event handlers from HTMLElement and also
defines the following:

onabort
The handler invoked when user aborts image loading.

onerror
The handler invoked when an error occurs during image
loading.

onl oad
Handler invoked when an image finishes loading.

Input an input element in an HTML form

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

52 JavaScript Pocket Reference


Input

Inherits From
HTMLElement

Synopsis

form, el ements[ i ]

form. name

Properties

Input inherits properties from HTMLElement and defines or


overrides the following:

checked
Whether a Checkbox or Radio element is checked.

defaul tChecked
A Checkbox or Radio element's default status.

defaul tVal ue
The default text displayed in an element.

form
The Form containing the element.
name
The name of a form element.

type
The type of a form element. JavaScript 1.1.

val ue
The value displayed or submitted by a form element. Nav-
igator 2; buggy in Internet Explorer 3-

Methods
Input inherits methods from HTMLElement and defines or
overrides the following:

blurO
Remove keyboard focus from a form element.

clickO
Simulate a mouseclick on a form element.

Alphabetical Object Reference 53


)

JavaArray

focus( )

Give keyboard focus to a form element.

sel ect(
Select the text in a form element.

Event Handlers
Input inherits event handlers from HTMLElement and defines
or overrides the following:

onbl ur
The handler invoked when a form element loses focus.

onchange
The handler invoked when a form element's value
changes.

oncl ick
The handler invoked when a form element is clicked.
JavaScript1.0; enhanced in JavaScript 1.1.

onfocus
The handler invoked when a form element gains focus.

JavaArray JavaScript representation of a Java array

Availability

Client-side Navigator 3

Synopsis

// The length of the array


javaarray. ength 1

// Read or write an array element


javaarraylindex]

Properties

1 ength
The number of elements in a Java array.

54 JavaScript Pocket Reference


JavaObject

JavaClass JavaScript representation of a Java class

Availability

Client-side Navigator 3

Synopsis

1/ Read or write a static Java field or method


jdvacl ass static_member
.

// Create a new Java object


new javaclassi . . . )

Properties

Each JavaClass object contains properties that have the same


names as the public static fields and methods of the Java class
it represents. These properties allow you to read and write

The properties that represent Java


the static fields of the class.
methods JavaMethod objects, which are JavaScript
refer to
objects that allow you to invoke Java methods. Each Java-
Class object has different properties; you can use a f or/i n
loop to enumerate them for any given JavaClass object.

JavaObject JavaScript representation of a Java object

Availability

Client-side Navigator 3

Synopsis

// Read or write an instance field or method


javaobject .member

Properties

Each JavaObject object contains properties that have the


same names as the public instance fields and methods (but
not the static or class fields and methods) of the Java object
it represents. These properties allow you to read and write

the value of public fields. The properties of a given Java-

Alphabetical Object Reference 55


JSObject

Object object obviously depend on the type of Java object it

represents. You can use the f or/i n loop to enumerate the


properties of any given JavaObject.

JavaPackage
JavaScript representation of a Java package

Availability

Client-side Navigator 3

Synopsis

II Refers to another JavaPackage


package. pa ckage_na me
// Refers to a JavaClass object
package. cl ass_name

Properties

The properties of a JavaPackage object are the names of the


JavaPackage objects and JavaClass objects that it contains.
These properties are different for each individual JavaPack-
age. Note that it is not possible to use the JavaScript f or/i n
loop to iterate over the list of property names of a Package
object. Consult a Java reference manual to determine the
packages and classes contained within any given package.

JSObject Java representation of a JavaScript object

Availability

A Java class in the netscape.javascript package included with


Navigator 3 and later

Synopsis

public final class netscape. javascri pt .JSObject

56 JavaScript Pocket Reference


1

Layer

Methods
cal {methodName, args[J)
Invoke a method of a JavaScript object.

eval (s)
Evaluate a string of JavaScript code.

getMember(/7<3/77e)
Read a property of a JavaScript object.

getSl ot( index)


Read an array element of a JavaScript object.

getWindow(app7et)
Return initial JSObject for browser window.

removeMember(/73/77e)
Delete a property of a JavaScript object.

setMember(/-73/77e, value)
Set a property of a JavaScript object.

setSl ot( index, val ue)


Set an array element of a JavaScript object.

toString( )

Return the string value of a JavaScript object.

Layer an independent layer in a DHTML document

Availability

Client-side Navigator 4

Synopsis

document. ayers[
1 /]

Constructor

new Layeriwidth, parent)

Alphabetical Object Reference 57


Layer

Properties

above
The layer above this one.

background
The background image of a layer.

below
The layer below this one.

bgCol or
The background color of a layer.

cl ip. bottom
The bottom of the layer's clipping region.

clip.height
The height of the layer's clipping region.

cl ip.l eft
The left edge of the layer's clipping region.

cl ip. right
The right edge of the layer's clipping region.

cl ip.top
The top of the layer's clipping region.

cl ip. width
The width of the layer's clipping region.

document
The Document object of a layer.

hidden
Whether a layer is hidden. Navigator 4; deprecated; use
Layer . vi sibi 1 i ty instead.

layers[]
The layers contained within a layer. Navigator 4; depre-
cated; use Layer .document . 1 ayers instead.

left
The X-coordinate of a layer.

name
The name of a layer. Client-side Navigator 4.

58 JavaScript Pocket Reference


Layer

pageX
The X-coordinate of a layer, relative to the page.

pageY
The Y-coordinate of a layer, relative to the page.

parentLayer
The parent of the layer.

si bl ingAbove
The sibling layer above this one.

sibl ingBel ow
The sibling layer below this one.

src
The source URL of a layer's content.

top
The Y-coordinate of a layer.

vi si bi 1 i ty
Whether a layer is visible.

window
The window that contains a layer.

x
The X-coordinate of a layer.

y
The Y-coordinate of a layer.

zlndex
Stacking order of a layer.

Methods
captureEvents(efe/7tmas/c)
Specify event types to be captured.

handl eEvent(e^e/?t )

Pass an event to the appropriate handler.

load(src, width)
Change layer contents and width.

Alphabetical Object Reference 59


Link
I moveAbove( target)
Move one layer above another.
moveBel ow( target)
Move one layer below another.

moveBy(c/x, dy)
Move a layer to a relative position.

moveTo(x, y)
Move a layer.

moveToAbsol ute(x, y)
Move a layer to page coordinates.
offset(c/x, dy)
Move a layer to a relative position. Deprecated; use
Layer moveBy(
. ) instead.

rel easeEvents(eve/7t/77as/c)
Stop capturing events.

resizeBy(div, dh)
Resize a layer by a relative amount.

resizeJoiwidth, height)
Resize a layer.

routeEvent(ei/e/7t)
Pass a captured event to the next handler.

Link a hypertext link

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
HTMLElement

Synopsis

document. inks[]1

document. links.length

60 JavaScript Pocket Reference


Link

Properties

Link inherits properties from HTMLElement and also defines


or overrides the following:

hash
The anchor specification of a link.

host
The hostname and port portions of a link.

hostname
The hostname portion of a link.

href
The complete URL of a link.

pathname
The path portion of a link.

port
The port portion of a link.

protocol
The protocol portion of a link.

search
The query portion of a link.

target
The target window of a hypertext link.

text
The text of a link. Navigator 4.

x
The X-coordinate of a link. Navigator 4.

y
The Y-coordinate of a link. Navigator 4.

Methods
Link inherits the methods of HTMLElement.

Alphabetical Object Reference 61


Location

Event Handlers
Link inherits the event handlers of HTMLElement and defines
special behavior for the following three:

oncl ick
The handler invoked when a link is clicked. JavaScript 1.0;
enhanced in JavaScript 1.1.
onmouseout
The handler invoked when the mouse leaves a link. Java-
Script 1.1.

onmouseover
The handler invoked when the mouse goes over a link.

Location represents and controls browser location

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

1ocation
window. ocation
1

Properties

The properties of a Location object refer to the various por-


tions of a URL.

hash
The anchor specification of the current URL.

host
The hostname and port portions of the current URL.

hostname
The hostname portion of the current URL.
href
The complete currently displayed URL.

pathname
The path portion of the current URL.

62 JavaScript Pocket Reference


Math
port
The port portion of the current URL.

protocol
The protocol portion of the current URL.

search
The query portion of the current URL.

Methods
rel oad( force)
Reload the current document. JavaScript 1.1.

repl dceiurl )

Replace one displayed document with another. JavaScript


1.1.

Math
a placeholder for mathematical functions and constants

Availability

Core JavaScript 1.0; ECMA-262

Synopsis

Math. constant
Math. function^ )

Constants
Math.E
The mathematical constant e.

Math.LNIO
The mathematical constant loge 10.

Math.LN2
The mathematical constant log^.
Math.LOGlOE
The mathematical constant log 10 e.

Math.L0G2E
The mathematical constant log2 e.

Alphabetical Object Reference 63


Math
I Math. PI
The mathematical constant n.

Math.SQRTl_2
The mathematical constant \/Jl .

Math.SQRT2
The mathematical constant Jl .

Static Functions
Math .abs(x)
Compute an absolute value.
Math.acos(x)
Compute an arc cosine.

Math .as in (x)


Compute an arc sine.

Math.atan(x)
Compute an arc tangent.

Math.atan2(x, y)
Compute the angle from the X-axis to a point.

Math .cei 1 (x)


Round a number up.

Math.cos(x)
Compute a cosine.

Math .exp(x)
Compute e x .

Math.fl oor(x)
Round a number down.
Math.log(x)
Compute a natural logarithm.

Math .max(a, b)
Return the larger of two values.

Math.minCa, b)
Return the smaller of two values.

64 JavaScript Pocket Reference


. ) 1 ]

MimeType
Math.pow(x, y)
Compute xv.

Math. random(
Return a pseudo-random number. JavaScript 1.1;
ECMA-262.
Math round(x)
Round to the nearest integer.

Math.sin(x)
Compute a sine.

Math sqrt(x)
.

Compute a square root.

Math.tan(x)
Compute a tangent.

MimeType represents a MIME data type

Availability

Client-side Navigator 3

Synopsis

navigator .mi meTy pes [ /


navigator .mi meTy pes ["type"]
navigator .mi meTy pes ength
.

Properties

description
A description of a MIME type.

enabl edPl ugin


The plugin that handles the MIME type.

suffixes
Common file suffixes for a MIME type.

type
The name of a MIME type.

Alphabetical Object Reference 65


Navigator

Navigator information about the browser in use

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1 and 1.2

Synopsis

navigator

Properties

navi gator. appCodeNa me


The code name of the browser.
navigator .appName
The application name of the browser.
navi gator. appVers ion
The platform and version of the browser.
navi gator. 1 anguage
The default language of the browser. Navigator 4.

navigator .mi meTy pes []


An array of supported MIME types. JavaScript 1.1; always
empty in Internet Explorer 4.

navigator.pl atform
The operating system the browser is running under.
JavaScript 1.2.

navigator.pl ugins[]
An array of installed plugins. JavaScript 1.1; always empty
in Internet Explorer 4.

navigator. system Language


The default language of the underlying system. Internet
Explorer 4.

navi gator. user Agent


The HTTP user-agent value.

navi gator. user Language


The language of the current user. Internet Explorer 4.

66 JavaScript Pocket Reference


O

Number
Functions
navigator. Java Enabled
Test whether Java is available. JavaScript 1.1.

navigator.pl ugins.refreshO
Make newly installed plugins available. Navigator 3.

navigator .preference (prefn a me, value)


Set or retrieve user preferences. Navigator 4; requires
Universal PreferencesRead privilege to query prefer-
ences; requires Uni versal Pref erencesWri te privilege
to set preference values.

navigator. savePreferencesO
Save the user's preferences. Navigator 4; requires
Uni versal Pref erencesWri te privilege.

nav i gator. taintEnabledO


Test whether data tainting is enabled. JavaScript 1.1;

deprecated.

Number support for numbers

Availability

Core JavaScript 1.1; ECMA-262

Synopsis

Number .constant

Constructor

new Number( va lue)


Number( va ue)
1

Constants
Number. MAX_VALUE
The maximum numeric value.
Number. MIN_VALUE
The minimum numeric value.

Alphabetical Object Reference 67


N

Object

Number. NaN
The special not-a-number value.

Number. N EGAT I VE_I N FI ITY


Negative infinity.

Number. POS I T I V E_I N F I N I TY


Infinity.

Methods
toStri ng(rac/7'x)
Convert a number to a string.

Object
a superclass that contains features of all JavaScript objects

Availability

Core JavaScript 1.0; ECMA-262; enhanced in JavaScript 1.1


and Navigator 4

Constructor

new Object( )

new Object( value)

Properties

constructor
An object's constructor function. JavaScript 1.1;
ECMA-262.

Methods
assign( va lue)
Overload the assignment operator. Navigator 3;

deprecated in favor of Object .watch( ).

eval (code)
Evaluate JavaScript code in a string. Navigator 3;

deprecated in favor of global eval ( ) function in


Navigator 4.

68 JavaScript Pocket Reference


]

Option

toString( )

Define an object's string representation.

unwatch(prop/7a/77e)
Remove a watchpoint. Navigator 4.

val ueOf(typehint)
The primitive value of the specified object. JavaScript 1.1;

ECMA-262.
watchipropname, hand! er)
Set a watchpoint. Navigator 4.

Option an option in a Select box

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
HTMLElement

Synopsis

select, opti ons[7

Properties

Option inherits the properties of HTMLElement and also


defines the following:

defaul tSel ected


Whether an object is selected by default.

index
The position of the option.

selected
Whether the option is selected.

text
The label for an option. JavaScript 1.0; read/write in
JavaScript 1.1.

Alphabetical Object Reference 69


]

Plugin

val ue
The value returned when the form is submitted.

Password a text input field for sensitive data

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Synopsis

form, name
form, el ements[ /

Properties

Password inherits properties from Input and HTMLElement


and defines or overrides the following:
val ue
User input to the Password object. JavaScript 1.0;

modified in JavaScript 1.2.

Methods
Password inherits methods from Input and HTMLElement.

Event Handlers
Password inherits methods from Input and HTMLElement.

Plugin describes an installed plugin

Availability

Client-side Navigator 3

70 JavaScript Pocket Reference


Radio

Synopsis

navigator.pl ugins[/]
navigator.pl ugins[ 'name 1

Properties

description
English description of a plugin.

f i 1 ename
The filename of the plugin program.

1 ength
The number of MIME types supported.
name
The name of a plugin.

PrivilegeManager Java class used by signed scripts

Availability

Client-side Navigator 4

Synopsis

netscape. security. Privil egeManager

Methods
di sabl ePri vi 1 eg e(pr f i/7 lege)
Disable a privilege.

enabl ePrivi 1eg e(pr / 1/7 lege)


Enable a privilege.

Radio a graphical radio button

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Alphabetical Object Reference 71


i

RegExp
I Inherits From
Input, HTMLElement

Synopsis

// A group of radio buttons with the same name


form.namel ]

Properties

Radio inherits properties from Input and HTMLElement, and


defines or overrides the following:

checked
Whether a Radio button is selected.

defaul tChecked
Initial state of a Radio button.

val ue
Value returned when form is submitted.

Methods
Radio inherits methods from Input and HTMLElement.

Event Handlers
Radio inherits event handlers from Input and HTMLElement
and defines or overrides the following:
oncl ick
The handler invoked when a Radio button is selected.

RegExp regular expressions for pattern matching

Availability

Core JavaScript 1.2

Constructor

new RegExp(patter/7, attributes)

72 JavaScript Pocket Reference


1

RegExp

Instance Properties
gl obal
Whether a regular expression matches globally. Not
implemented in IE 4.
ignoreCase
Whether a regular expression is case-insensitive. Not
implemented in IE 4.

1 astlndex
The character position after the last match. Not imple-
mented in IE 4.
source
The text of the regular expression.

Static Properties

RegExp. %n
The text that matched the nth subexpression.
RegExp. input or RegExp. $_
The input buffer for pattern matching. Non-functional in
IE 4.

RegExp. lastMatch or RegExp["$&" ]

The text of the last successful pattern match. Not imple-


mented in IE 4.
RegExp. astParen or RegExp["$+"]
The text that matched the last subexpression. Not imple-
mented in IE 4.
/M
RegExp. leftContext or RegExp["$ ]

The text before the last match. Not implemented in IE 4.

RegExp. mul ti 1 ine or RegExp[ "$*"]


Whether matches are performed in multi-line mode. Not
implemented in IE 4.
,M
RegExp. rightContext or RegExp["$ ]

The text after the last match. Not implemented in IE 4.

Alphabetical Object Reference 73


1

Reset

Methods
compi einewpattern attributes)
,

Change a regular expression.


exec(string)
General-purpose pattern matching. Buggy in IE 4.

test(string)
Test whether a string contains a match.

Reset a button to reset a form's values

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Synopsis

form, name
form, el ements[ /]

Properties

Reset inherits properties from Input and HTMLElement and


defines or overrides the following:

val ue
The label of a Reset button.

Methods
Reset inherits the methods of Input and HTMLElement.

Event Handlers
Reset inherits the event handlers of Input and HTMLElement
and defines or overrides the following:

74 JavaScript Pocket Reference


..

Screen

oncl ick
The handler invoked when a Reset button is clicked.
JavaScript 1.0; enhanced in JavaScript 1.1.

Screen provides information about the display

Availability

Client-side JavaScript 1.2

Synopsis

screen

Properties

screen .avai 1 Height


The available height of the screen.

screen .avai 1 Left


The first available horizontal pixel. Navigator 4.

screen .avai Top 1

The first available vertical pixel. Navigator 4.

screen avai Width 1

The available width of the screen.


screen .col orDepth
The depth of the web browser's color palette.

screen height
The height of the screen.

screen .pixel Depth


The color depth of the screen. Navigator 4.

screen .width
The width of the screen.

Alphabetical Object Reference 75


Select

Select a graphical selection list

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Synopsis

form. element_name
form, el ementsE/ ]

Properties

Select inherits properties from Input and HTMLElement and


defines or overrides the following:

1 ength
The number of options in a Select object.

optionsE]
The choices in a Select object. JavaScript 1.0; enhanced in
JavaScript 1.1.

1
se ectedlndex
The selected option. JavaScript 1.0; writeable in JavaScript
1.1.

type
Type of form element. JavaScript 1.1.

Methods
Select inherits the methods of Input and HTMLElement.

Event Handlers
Select inherits event handlersfrom Input and HTMLElement
and defines or overrides the following:
onchange
The handler invoked when the selection changes.

76 JavaScript Pocket Reference


String

String support for strings

Availability

Core JavaScript 1.0; enhanced in Navigator 3

Constructor

new String( value) // JavaScript 1.1

Properties

length
The length of a string. JavaScript 1.0; ECMA-262.

Methods
anchoriname)
Add an HTML anchor to a string.

big()
Make a string <BIG>.

blinkO
Make a string <BLINK>.

boldO
Make a string bold with <B>.

charAt(A?)
Get the /7th character from a string. JavaScript 1.0; ECMA-
262.

charCodeAt(/7)
Get the nth character code from a string. JavaScript 1.2;

ECMA-262.
concat( va lue, . . . )

Concatenate strings. JavaScript 1.2.

fixedO
Make a string fixed- width with <TT>.

fontcol or(color)
Set a string's color with <F0NT>.

Alphabetical Object Reference


i ) ) )

String

fontsize(sfze)
Set a string's font size with <F0NT>.

indexOf (substr i ng, start)


Search a string. JavaScript 1.0; ECMA-262.
i ta 1 i cs (

Make a string italic with <I>.

1 a st IndexOf (substring, start)


Search a string backwards. JavaScript 1.0; ECMA-262.
1 ink(href)
Add a hypertext link to a string.

match(regexp)
Find one or more regular expression matches. JavaScript
1.2.

repl ace {regexp, repl a cement)


Replace substring(s) matching a regular expression.
JavaScript 1.2.

search(regexp)
Search for a regular expression. JavaScript 1.2.

sMceistart, end)
Extract a substring. JavaScript 1.2.

smal 1 (

Make a string <SMALL>.

spl tide! imiter)


Break a string into an array of strings. JavaScript 1.1;

ECMA-262.

stri ke(
Strike out a string with <STRIKE>.

sub()
Make a string a subscript with <SUB>.

substri ng( from, to)


Return a substring of a string. JavaScript 1.0; ECMA-262.

substristart, length)
Extract a substring. JavaScript 1.2.

78 JavaScript Pocket Reference


. e

Style

sup( )

Make a string a superscript with <SUP>.

tol_owerCase( )

Convert a string to lowercase. JavaScript 1.0; ECMA-262.


toUpperCase( )

Convert a string to uppercase. JavaScript 1.0; ECMA-262.

Static Methods
String. f romCharCode(ci , c2, . . . )

Create a string from character encodings. JavaScript 1.2;

ECMA-262.

Style cascading style sheet attributes

Availability

Client-side JavaScript 1.2

Synopsis

// Navigator
document, cl asses .cl assName. tagName
document, ids .elementName
document. tags tagName
document, contextual (...)

// Internet Explorer
html Element styl .

Properties

The Style object has properties corresponding to each of the


CSS attributes supported by the browser.

Methods
borderWidths( top, right, bottom, left)
Set all border width properties. Navigator 4.

Alphabetical Object Reference 79


Submit

marginsUop, right, bottom, left)


Set all margin properties. Navigator 4.

paddings( top, right, bottom, left)


Set all padding properties. Navigator 4.

Submit a button to submit a form

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Synopsis

form. name
form, el ements[/ ]

Properties

Submit inherits properties from Input and HTMLElement and


defines or overrides the following:

val ue
The label of a Submit button.

Methods
Submit inherits the methods from Input and HTMLElement.

Event Handlers
Submit inherits event handlers from Input and HTMLElement
and defines or overrides the following:
oncl ick
Invoked when a Submit button is clicked. JavaScript 1.0;
enhanced in JavaScript 1.1.

80 JavaScript Pocket Reference


Textarea

Text a graphical text input field

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Synopsis

form, name
form, el ements[/]

Properties

Text inherits properties from Input and HTMLElement and


defines or overrides the following:

val tie

User input to the Text object.

Methods
Text inherits the methods of Input and HTMLElement.

Event Handlers
Text inherits the event handlers of Input and HTMLElement
and defines or overrides the following:
onchange
The handler invoked when input value changes.

Textarea a multiline text input area

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1

Inherits From
Input, HTMLElement

Alphabetical Object Reference 81


]

URL

Synopsis

form, name
form, el ements[ /

Properties

Textarea inherits the properties of Input and HTMLElement


and defines or overrides the following:
val ue
User input to the Textarea object.

Methods
Textarea inherits the methods of Input and HTMLElement.

Event Handlers
Textarea inherits the event handlers of Input and HTMLEle-
ment and defines or overrides the following:

onchange
The handler invoked when input value changes.

URL see Link, Location, or Document. URL

Window a web browser window or frame

Availability

Client-side JavaScript 1.0; enhanced in JavaScript 1.1 and 1.2

Synopsis

self
window
window, f rames[/

Properties

The Window object defines the following properties. Non-


portable, browser-specific properties are listed separately-
after this list:

82 JavaScript Pocket Reference


Window
cl osed
Whether a window has been closed. JavaScript 1.1.

defaul tStatus
The default status line text.

document
The Document of the window.
f rames[]
List of frames within a window.

hi story
The History of the window.
1 ength
The number of frames in the window.
1 ocation
The URL of the window.
name
The name of a window. JavaScript 1.0; read/write in
JavaScript 1.1.

navigator
A reference to the Navigator object.

off screenBufferi ng
Whether window updates are buffered. JavaScript 1.2.

opener
The window that opened this one. JavaScript 1.1.

parent
The parent of a frame.

screen
Information about the screen. JavaScript 1.2.

self
The window itself.

status
Specify a transient status-line message.

top
The window of a frame.

Alphabetical Object Reference 83


Window
window
The window itself.

Navigator Properties
crypto
Reference to the Crypto object. Navigator 4.04 and later.

innerHeight
The height of the document display area. Navigator 4;
Universal BrowserWri te privilege required to set to less
than 100 pixels.

innerWidth
The width of the document display area. Navigator 4;
Uni versal BrowserWri te privilege required to set to less
than 100 pixels.

Java
The Java.* LiveConnect package. Navigator 3.

1 ocationbar
The visibility of the browser's location bar. Navigator 4;
Universal BrowserWri te privilege required to change
visibility.

menubar
The visibility of the browser's menubar. Navigator 4;
Universal BrowserWri te privilege required to change
visibility.

netscape
The netscape.* LiveConnect Java package. Navigator 3.

outerHeight
The height of the window area. Navigator 4;
Uni versal BrowserWri te privilege required to set to less

than 100 pixels.

outerWidth
The width of the window. Navigator 4;
Universal BrowserWri te privilege required to set
to less than 100 pixels.

84 JavaScript Pocket Reference


Window
Packages
LiveConnect packages of Java classes. Navigator 3.

pageXOffset
The current horizontal scroll position. Navigator 4.

pageYOffset
The current vertical scroll position. Navigator 4.

personal bar
The visibility of the browser's personal bar. Navigator 4;
Uni versal BrowserWri te privilege required to change
visibility.

screenX
The X-coordinate of a window on the screen. Navigator 4.

screenY
The Y-coordinate of a window on the screen. Navigator 4.

scrol 1 bars
The visibility of the browser's scroll bars. Navigator 4;
UniversalBrowserWrite privilege required to change
visibility.

statusbar
The visibility of the browser's status line. Navigator 4;
UniversalBrowserWrite privilege required to change
visibility.

sun
The sun.* LiveConnect Java package. Navigator 3-

tool bar
The visibility of the browser's toolbar. Navigator 4;

Uni versal BrowserWri te privilege required to change


visibility.

Internet Explorer Properties

cl ientlnformation
Synonym for W i ndow . nav i gator . Internet Explorer 4.

event
Describes the most recent event. Internet Explorer 4.

Alphabetical Object Reference 85


i )

Window

Methods
The Window object has the following portable methods.
Non-portable, browser-specific methods are listed after
this list.

al ert(message)
Display a message in a dialog box.

blurO
Remove keyboard focus from a top-level window.
JavaScript 1.1.

clearlnterval (interval Id)


Stop periodically executing code. JavaScript 1.2.

cl earTimeout( timeoutld)
Cancel deferred execution.

cl ose(
Close a browser window.

conf rm(question)
Ask a yes-or-no question.

focus( )

Give keyboard focus to a top-level window. JavaScript


1.1.

moveBy(c/x, dy)
Move a window to a relative position. JavaScript 1.2;
Navigator 4 requires UniversalBrowserWrite privilege
to move the window off-screen.

moveTo(x, y)
Move a window to an absolute position. JavaScript 1.2;

Navigator 4 requires UniversalBrowserWrite privilege


to move the window off-screen.

open(i/r7, name, features, replace)


Open a new browser window or locate a named window.
JavaScript 1.0; enhanced in JavaScript 1.1.

prompt (message, default)


Get string input in a dialog.

86 JavaScript Pocket Reference


1 . )
.

Window
resizeBy(c/iv, dh)
Resize a window by a relative amount. JavaScript 1.2.
Navigator 4 requires UniversalBrowserWrite privilege
to set either width or height to less than 100 pixels.

re si zeJoiwidth, height)
Resize a window. JavaScript 1.2; Navigator 4 requires
Universal BrowserWri te privilege to set either width or
height to less than 100 pixels.

scrol (x, y)
Scroll a document in a window. JavaScript 1.1; deprecated
in JavaScript 1 .2 in favor of s c r o 1 1 To ( )

scrol 1 By (g(x, dy)


Scroll the document by a relative amount. JavaScript 1.2.

scrollTo(x, y)
Scroll the document. JavaScript 1.2.

setlnterval {code, interval)


setlnterval func, ( interval args
, . .

Periodically execute specified code. JavaScript 1.2;


Internet Explorer 4 supports only the first form of
this method.

setTimeout( code, del ay)


Defer execution of code.

Navigator 4 Methods
dtob(str64)
Decode base-64 encoded data.

backO
Go back to previous document.

btod(data)
Encode binary data using base-64 ASCII encoding.
captureEventsieventmask)
Specify event types to be captured.

disableExternalCaptureO
Disable cross-server event capturing. Requires
Uni versal BrowserWri te privilege.

Alphabetical Object Reference 87


)

Window
enabl e External Capture( )

Enable cross-server event capturing. Requires


Universal BrowserWri te privilege.

find (target, caseSensiti ve, backwards)


Search the document.

forward( )

Go forward to next document.


handl eEvent(ei/e/7t )

Pass an event to the appropriate handler.

home(
Display the home page.

print( )

Print the document.

rel easeEventsi even tmask)


Stop capturing events.

routeEvent(e\/e/7t )

Pass a captured event to the next handler.

setHotkeys(e/7<3t>7ec/)
Allow or disallow keyboard shortcuts. Requires
Uni versal BrowserWri te privilege.

setResizabl e(resizable)
Allow or disallow window resizing. Requires
Universal BrowserWri te privilege.

setZ0ptions(opt7on)
Control window stacking. Requires
Uni versal BrowserWri te privilege.

stop( )

Stop loading the document.

Internet Explorer Methods

navigate(i/r7 )

Load a new URL. Internet Explorer 3-

88 JavaScript Pocket Reference


Window
Event Handlers
onbl ur
The handler invoked when the window loses keyboard
focus. JavaScript 1.1.

ondragdrop
The handler invoked when the user drops items in the
window. Navigator 4.
onerror
The handler invoked when a JavaScript error occurs.
JavaScript 1.1.

onfocus
Invoked when window is given focus. JavaScript 1.1.

onload
The handler invoked when a document finishes loading.

onmove
The handler invoked when a window is moved. Navigator
4; not supported on Navigator 4 Unix platforms.

onresize
The handler invoked when a window is resized.
JavaScript 1.2.

onunl oad
The handler invoked when the browser leaves a page.

Alphabetical Object Reference 89


More Titles

Web Programming
from O'Reilly
^
WebMaster in a Nutshell, CGI Programming on the
Deluxe Edition World Wide Web
By O'Reilly & Associates, Inc. By Shishir Gundavaram
1st Edition September 1997 1st Edition March 1996

374 pages, includes CD-ROM & book 450 pages, ISBN 1-56592-168-2
ISBN 1-56592-305-7

JavaScript: The Definitive


HTML: The Definitive Guide, Guide, 3rd Edition
2nd Edition By David Flanagan & Dan Shafer
By Chuck Musciano & Bill Kennedy 3rd Edition June 1998
2nd Edition May 1997 800 pages, ISBN 1-56592-392-8
552 pages, ISBN 1-56592-235-2

Learning VBScript
Dynamic HTML: The Definitive By Paul Lomax
Reference 1st Edition July 1997
By Danny Goodman 616 pages, includes CD-ROM
1st Edition July 1998 ISBN 1-56592-247-6
1088 pages, ISBN 1-56592-494-0

Web Client Programming


Frontier: The Definitive Guide with Perl
By Matt Neuburg By Clinton Wong
1st Edition February 1998 1st Edition March 1997
618 pages, 1-56592-383-9 228 pages, ISBN 1-56592-2 14-X

WebMaster in a Nutshell Information Architecture


By Stephen Spainhour & Valerie Quercia tor the World Wide Web
1st Edition October 1996 By Louis Rosenfeld & Peter Morville
374 pages, ISBN 1-56592-229-8 1st Edition January 1998
226 pages, ISBN 1-56592-282-4

OREILLY*
to order: 800-998-9938 • [email protected] • http://www.oreilly.com/

Our products are available at a bookstore or software store near you.

for information: 800-998-9938 • 707-829-0515 • [email protected]


World Wide Web/Internet/Programming Languages

O'REILLY*

JavaScript Pocket Reference


JavaScript is a powerful, object-based scripting
language that can be embedded directly in HTML
pages. It allows yoti to create dynamic, interactive
Web-based applications that run completely within
a Web browser —JavaScript is the language of choice for
developing Dynamic HTML (DHTML) content. JavaScript can be
integrated effectively with CGI and Java to produce sophisticated
Web applications, although, in many cases, JavaScript eliminates
the need for complex CGI scripts and Java applets altogether.

The JavaScript Pocket Reference is a companion volume to

JavaScript: The Definitive Guide, 3rd Edition. This small book,


covering JavaScript 1.2, the version of the language supported
by Netscape Navigator 4 and Microsoft Internet Explorer 4, is

a handy reference guide to this popular language for Web


development. It provides a complete overview of the core
JavaScript language and contains summaries of both core and
client-side objects, methods, and properties.

David Flanagan is an author, consulting computer programmer,


user interface designer, and trainer. His other books include the
bestselling JavaScript: The Definitive Guide and Java in a Nutshell

Visit O'Reilly on the Web at www.oreilly.com

J7^> Printed on
US $7.95
ISBN 1-56592-521-1 CAN $11.95 {£3$ Recycled Paper
90000

mi 36920 92521"
9 ,
781565"925212 6 7

You might also like