Book HomeMac OS X for Unix GeeksSearch this book

Chapter 24. Client-Side JavaScript Reference

This part of the book is a reference section that documents the classes, methods, properties, and event handlers defined by web browsers that support client-side JavaScript. These classes, methods, and properties form the de facto standard called the DOM Level 0 API. Beginning scripters and programmers writing with backward compatibility in mind will use this reference section in conjunction with the core JavaScript reference of Part III. The introduction and sample reference page explain how to use and get the most out of this reference section. Take the time to read this material carefully, and you will find it easier to locate and use the information you need!

This reference section is arranged alphabetically. The reference pages for the methods and properties of classes are alphabetized by their full names, which include the names of the classes that define them. For example, if you want to read about the submit( ) method of the Form class, you would look under "Form.submit," not just "submit."

To save space in this enlarged fourth edition of the book, most properties in this reference section do not have reference pages of their own (all methods and event handlers do have their own reference pages, however). Instead, simple properties are completely documented in the reference page for the class that defines them. For example, you can read about the images[] property of the Document class in the "Document" reference page. Nontrivial properties that require substantial explanation do have reference pages of their own, and you'll find a cross-reference to these pages within the reference page of the class or interface that defines the properties. For example, when you look up the cookie property in the "Document" reference page or the status property in the "Window" reference page, you'll find a short description of the property and a reference to pages named "Document.cookie" and "Window.status."

Client-side JavaScript has a number of global properties and functions, such as window, history, and alert( ). In client-side JavaScript, a Window object serves as the global object, and the "global" properties and functions of client-side JavaScript are actually properties of the Window class. Therefore, in this client-side reference section, global properties and functions are documented in the "Window" reference page or under names such as "Window.alert( )."

Sometimes you may find that you don't know the name of the class or interface that defines the method or property you want to look up, or you may not be sure which of the three reference sections to look up a class or interface in. Part VI of this book is a special index designed to help with these situations. Look up the name of a class, method, or property, and it will tell you which reference section to look in and which class to look under in that section. For example, if you look up "Button," it will tell you that the Button class is documented in this client-side reference section. And if you look up the name "alert," it will tell you that alert( ) is a method of the client-side Window class.

Once you've found the reference page you're looking for, you shouldn't have much difficulty finding the information you need. Still, you'll be able to make better use of this reference section if you understand how the reference pages are written and organized. What follows is a sample reference page titled "Sample Entry" that demonstrates the structure of each reference page and tells you where to find various types of information within the pages. Take the time to read this page before diving into the rest of the reference material.

Sample Entryhow to read client-side reference pages

Availability

Availability

Inherits from/Overrides

Inherits from

Title and Short Description

Every reference entry begins with a title block like that above. The entries are alphabetized by title. The short description, shown next to the title, gives you a quick summary of the item documented in the entry; it can help you quickly decide if you're interested in reading the rest of the page.

Availability

The information in this section tells you when a class, method, or event handler was introduced. For some less portable items, this section specifies which versions of Netscape and Internet Explorer support it. If the item is well supported by web browsers and support was added by Netscape and IE within the same browser generation, this section specifies its availability in terms of a version of core JavaScript. You can use the tables in Chapter 1 to determine the particular releases of Netscape and Internet Explorer to which these versions correspond. Of course, since most properties do not have their own reference pages, they do not have availability information. If the availability of a property is different from the availability of the class that defines it, however, this fact is noted in the description of the property.

Inherits from

If a class inherits from a superclass, that information is shown in the "Inherits from" section. As described in Chapter 8, JavaScript classes can inherit properties and methods from other classes. For example, the Button class inherits from Input, which in turn inherits from HTMLElement. When you see this inheritance information, you may also want to look up the listed superclasses.

Synopsis

Every reference page has a "Synopsis" section that shows how you might use the class, method, or event handler in your code. For example, the synopsis for the Form class is:

document.form_name
document.forms[form_number] 

This synopsis shows two different ways of referring to a Form object. Text in this font must be typed exactly as shown. The italic font indicates text that is to be replaced with something else. form_name should be replaced with the name of a form, and form_number should be replaced with the index of the form in the forms[] array. Similarly, document should be replaced in these synopses with a reference to a Document object. By looking at the "Synopsis" section of the "Document" reference page, we discover that it also has two forms:

document
window.document 

That is, you can replace document with the literal document or with window.document. If you choose the latter, you'll need to look up the synopsis of the Window class to find out how to refer to a Window -- that is, what to replace window with.

Arguments

If a reference page documents a method, the "Synopsis" section is followed by an "Arguments" subsection that describes the arguments to the method. If the method has no arguments, this subsection is simply omitted.

arg1
The arguments are described in a list here. This is the description for argument arg1, for example.

arg2
And this is the description for argument arg2.

Returns

This section explains the method's return value. If the method does not return a value, this subsection is omitted.

Constructor

If the reference page documents a class that has a constructor method, this section shows you how to use the constructor method to create instances of the class. Since constructors are a type of method, the "Constructor" section looks a lot like the "Synopsis" section of a method's reference page and has an "Arguments" subsection as well.

Properties

If the reference page documents a class, the "Properties" section lists and documents the properties defined by that class. In this client-side reference section, only particularly complex properties have reference pages of their own.

prop1
This is documentation for property prop1, including its type, its purpose or meaning, and whether it is read-only or read/write.

prop2
This is the same for prop2.

Methods

The reference page for a class that defines methods includes a "Methods" section that lists the names of the methods and provides a short description of each. Full documentation for each method is found in a separate reference page.

Event Handlers

The reference page for a class that defines event handlers includes an "Event Handlers" section that lists the names of the handlers and provides a short description of each. Full documentation for each event handler is found in a separate reference page.

HTML Syntax

A number of client-side JavaScript classes have analogs in HTML. The reference pages for these classes include a section that shows the annotated HTML syntax used to create an HTML element that corresponds to a JavaScript object.

Description

Most reference pages contain a "Description" section, which is the basic description of the class, method, or event handler that is being documented. This is the heart of the reference page. If you are learning about a class, method, or handler for the first time, you may want to skip directly to this section and then go back and look at previous sections such as "Arguments," "Properties," and "Methods." If you are already familiar with an item, you probably won't need to read this section and instead will just want to quickly look up some specific bit of information (for example, from the "Arguments" or "Properties" sections).

In some entries, this section is no more than a short paragraph. In others, it may occupy a page or more. For some simple methods, the "Arguments" and "Returns" sections document the method sufficiently by themselves, so the "Description" section is omitted.

Example

A few pages include an example that shows typical usage. Most pages do not contain examples, however -- you'll find those in first half of this book.

Bugs

When an item doesn't work quite right, this section describes the bugs. Note, however, that this book does not attempt to catalog every bug in every version and implementation of client-side JavaScript.

See Also

Many reference pages conclude with cross-references to related reference pages that may be of interest. Most of these cross references are to other reference pages in this client-side reference section. Some are to individual property descriptions contained within a class reference page, however, and others are to related reference pages in the DOM reference section or to chapters in the first two parts of the book.

Anchorthe target of a hypertext link

Availability

JavaScript 1.2

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

document.anchors[i] 
document.anchors.length

Properties

Anchor inherits properties from HTMLElement and defines or overrides the following:

name
Contains the name of an Anchor object. The value of this property is initially set by the name attribute of the <a> tag.

text [Netscape 4]
This property specifies the plain text, if any, between the <a> and </a> tags of an anchor. Note that this property works correctly only if there are no intervening HTML tags between the <a> and </a> tags. If there are other HTML tags, the text property may contain only a portion of the anchor text.

HTMLElement.innerText provides the IE 4 equivalent of this Netscape-specific property.

HTML Syntax

An Anchor object is created by any standard HTML <a> tag that contains a name attribute:

<a
  name="name"  // Links may refer to this anchor by this name
>
text
</a>

Description

An anchor is a named location within an HTML document. Anchors are created with an <a> tag that has a name attribute specified. The Document object has an anchors[] array property that contains Anchor objects that represent each of the anchors in the document. This anchors[] array has existed since JavaScript 1.0, but the Anchor object was not implemented until JavaScript 1.2. Therefore, the elements of anchors[] were null until JavaScript 1.2.

Note that the <a> tag used to create anchors is also used to create hypertext links. Although hypertext links are often called anchors in HTML parlance, they are represented in JavaScript with the Link object, not with the Anchor object. In the DOM reference section of this book, however, both anchors and links are documented under HTMLAnchorElement.

See Also

anchors[] property of the Document object, Link; HTMLAnchorElement in the DOM reference section

Appletan applet embedded in a web page Applet object

Availability

JavaScript 1.1

Synopsis

document.applets[i] 
document.appletName

Properties

The properties of an Applet object are the same as the public fields of the Java applet it represents.

Methods

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

Description

The Applet object represents a Java applet embedded in an HTML document. The properties of the Applet object represent the public fields of the applet, and the methods of the Applet object represent the public methods of the applet. LiveConnect technology in Netscape and ActiveX technology in Internet Explorer allow JavaScript programs to use the Applet object to read and write the fields and invoke the methods of the corresponding Java applet. See Chapter 22 for details.

Remember that Java is a strongly typed language. This means that each field of an applet has been declared to have a specific data type, and setting it to a value of some other type causes a runtime error. The same is true of applet methods: each argument has a specific type, and arguments cannot be omitted as they can be in JavaScript.

See Also

JavaObject; Chapter 22

Areasee Link

Buttona graphical push buttonButton object

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.button_name 
form.elements[i]

Properties

Button inherits properties from Input and HTMLElement and defines or overrides the following:

value
A string property that specifies the text that appears in the button. The value of this property is specified by the value attribute of the HTML <input> tag that creates the button. In browsers that cannot reflow document content, this property may be read-only.

Methods

Button inherits methods from Input and HTMLElement.

Event Handlers

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

onclick
Invoked when the button is clicked.

HTML Syntax

A Button element is created with a standard HTML <input> tag:

<form>
    ...
  <input
    type="button"          // Specifies that this is a button
    value="label"          // The text that is to appear within the button
                           // Specifies the value property
    [ name="name" ]        // A name you can use later to refer to the button
                           // Specifies the name property
    [ onclick="handler" ]  // JavaScript statements to be executed when the button
                           // is clicked
  >
    ...
</form>

Button objects can also be created with the HTML 4 <button> tag:

<button id="name"
        onclick="handler">
label
</button>

Description

The Button element represents a graphical push button in a form within an HTML document. The value property contains the text displayed by the button. The name property is the name the button may be referred to as. The onclick event handler is invoked when the user clicks on the button.

Usage

Use a Button element whenever you want to allow the user to trigger some action on your web page. You can sometimes use a Link object for the same purpose, but unless the desired action is to follow a hypertext link, a Button is a better choice than a Link, because it makes it more explicit to the user that there is something to be triggered.

Note that the Submit and Reset elements are types of Buttons that submit a form and reset a form's values. Often these default actions are sufficient for a form, and you do not need to create any other types of buttons.

Example

<form name="form1">
    <input type="button"
        name="press_me_button"
        value="Press Me"
        onclick="username = prompt('What is your name?',")"
    >
</form>

See Also

Form, HTMLElement, Input, Reset, Submit; HTMLInputElement in the DOM reference section

Button.onclickthe handler invoked when a Button is clicked

Availability

JavaScript 1.0

Synopsis

<input type="button" value="button-text" onclick="handler"> 
button.onclick

Description

The onclick property of a Button object refers to an event handler function that is invoked when the user clicks on the button. See HTMLElement.onclick for complete details. Note, however, that Button.onclick has been supported since JavaScript 1.0, unlike the generalized HTMLElement.onclick handler.

See Also

HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Checkboxa graphical checkbox

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

A single Checkbox element with a unique name may be referenced in either of these ways:

form.checkbox_name
form.elements[i] 

When a form contains a group of checkboxes with the same name, they are placed in an array and may be referenced as follows:

form.checkbox_name[j]
form.checkbox_name.length 

Properties

Checkbox inherits properties from Input and HTMLElement and defines or overrides the following:

checked
A read/write boolean property. If the checkbox is checked, the checked property is true. If the checkbox is not checked, checked is false.

If you set checked to true, the checkbox appears checked. Similarly, if you set this property to false, the checkbox appears unchecked. Note that setting the checked property does not cause the Checkbox element's onclick event handler to be invoked.

defaultChecked
A read-only boolean that specifies the initial state of the checkbox. It is true if the checkbox is initially checked -- i.e., if the checked attribute appears in the checkbox's HTML <input> tag. If this attribute does not appear, the checkbox is initially unchecked and defaultChecked is false.

value
A read/write string property that specifies the text passed to the web server if the checkbox is checked when the form is submitted. The initial value of value is specified by the value attribute of the checkbox's HTML <input> tag. If no value attribute is specified, the default value string is "on".

Note that the value field does not specify whether the checkbox is selected; the checked property specifies the current state of the checkbox. When defining a group of related checkboxes that share the same name in a form that is submitted to the server, it is important that each be given a distinct value attribute.

Methods

Checkbox inherits the methods of Input and HTMLElement.

Event Handlers

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

onclick
Invoked when the checkbox is clicked.

HTML Syntax

A Checkbox element is created with a standard HTML <input> tag. Multiple Checkbox elements are often created in groups by specifying multiple <input> tags that have the same name attribute.

<form>
    ...
  <input
    type="checkbox"        // Specifies that this is a checkbox
    [ name="name" ]        // A name you can use later to refer to this checkbox
                           // or to the group of checkboxes with this name
                           // Specifies the name property
    [ value="value" ]      // The value returned when this checkbox is selected
                           // Specifies the value property
    [ checked ]            // Specifies that the checkbox is initially checked
                           // Specifies the defaultChecked property
    [ onclick="handler" ]  // JavaScript statements to be executed
  >                        // when the checkbox is clicked
label                      // The HTML text that should appear next to the checkbox
    ...
</form>

Description

The Checkbox element represents a single graphical checkbox in an HTML form. Note that the text that appears next to the checkbox is not part of the Checkbox element itself and must be specified externally to the Checkbox's HTML <input> tag.

The onclick event handler allows you to specify JavaScript code to be executed when the checkbox is checked or unchecked. You can examine the checked property to determine the state of the checkbox and set this property to check or uncheck the checkbox. Note that setting checked changes the graphical appearance of the checkbox but does not invoke the onclick event handler.

It is good programming style to specify the name attribute for a checkbox; this is mandatory if the checkbox is part of a form that submits data to a CGI script running on a web server. Specifying a name attribute sets the name property and allows you to refer to the checkbox by name (instead of as a member of the form elements array) in your JavaScript code, which makes the code more modular and portable.

For example, if the name attribute of a checkbox in form f is "opts", f.opts refers to the Checkbox element. Checkbox elements are often used in related groups, however, and each member of the group is given the same name attribute (the shared name defines the members of the group). In this case, JavaScript places each Checkbox element in the group in an array, and the array is given the shared name. If, for example, each of a group of checkboxes in form f has its name attribute set to "opts", f.opts is an array of Checkbox elements, and f.opts.length is the number of elements in the array.

You can set the value attribute or the value property of a checkbox to specify the string that is passed to the server if the checkbox is checked when the form is submitted. For a single checkbox used alone, the default value of "on" is usually adequate. When multiple checkboxes with the same name are used, each should specify a distinct value so a list of values from selected checkboxes can be passed to the server.

Usage

Checkbox elements can present the user with one or more options. This element type is suitable for presenting non-mutually exclusive choices. Use the Radio element for mutually exclusive lists of options.

See Also

Form, HTMLElement, Input, Radio; HTMLInputElement in the DOM reference section

Checkbox.onclickthe handler invoked when a checkbox is selected

Availability

JavaScript 1.0

Synopsis

<input type="checkbox" onclick="handler"> 
checkbox.onclick

Description

The onclick property of a Checkbox object refers to an event handler function that is invoked when the user clicks on the checkbox. See HTMLElement.onclick for complete details. Note, however, that Checkbox.onclick has been supported since JavaScript 1.0, unlike the generalized HTMLElement.onclick handler.

See Also

HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Documentrepresents an HTML document

Availability

JavaScript 1.0; enhanced in JavaScript 1.1, Netscape 4, and IE 4

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

window.document 
document 

Properties

Document inherits properties from HTMLElement and defines the following properties. Netscape and Internet Explorer both define a number of incompatible Document properties that are used mostly for DHTML; they are listed separately after these properties.

alinkColor
alinkColor is a string property that specifies the color of activated links in document. Browsers may display this color between the times that the user presses and releases the mouse button over the link. The alink attribute of the <body> HTML tag specifies the initial value of this property. This property may be set, but only in the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

anchors[]
An array of Anchor objects, one for each anchor that appears in document. An anchor is a named position within the document that can serve as the target of a hypertext link. The anchors[] array has anchors.length elements, numbered from zero to anchors.length-1. Do not confuse anchors with hypertext links, which are represented in JavaScript by the Link objects in the Document.links[] array.

Prior to JavaScript 1.2, the Anchor object was unimplemented, and the elements of anchors[] were all null.

applets[] [ JavaScript 1.1]
An array of Applet objects, one for each applet that appears in the document. You can use the Applet object to read and write all public variables in the applet, and you can invoke all of the applet's public methods. If an <applet> tag has a name attribute, the applet may also be referred to by using the name as a property of document or as an index into the applets array. Thus, if the first applet in a document has name="animator", you can refer to it in any of these ways:

document.applets[0]
document.animator
document.applets["animator"]
bgColor
A string property that specifies the background color of document. The initial value of this property comes from the bgcolor attribute of the <body> tag. The background color may be changed by assigning a value to bgColor. Unlike the other color properties, bgColor can be set at any time. See also the color properties of HTMLBodyElement in the DOM reference section.

cookie
A string that is the value of a cookie associated with this document. See the Document.cookie reference page.

domain
A string that specifies the document's Internet domain. Used for security purposes. JavaScript 1.1 and higher. See the Document.domain reference page.

embeds[] [ JavaScript 1.1]
An array of objects that represent data embedded in the document with the <embed> tag. The objects in the embeds[] array do not refer to the embedded data directly but refer instead to the object that displays that data. You can use the objects in the embeds[] array to interact with embedded data. The way you do this, however, is specific to the type of embedded data and the plugin or ActiveX control used to display it. Consult the developer's documentation for the plugin or ActiveX control to learn whether it can be scripted from JavaScript and, if so, what the supported APIs are.

Document.plugins[] is a synonym for Document.embeds[]. Do not confuse it with Navigator.plugins[].

fgColor
A string property that specifies the default color of text in document. The initial value of this property is from the text attribute of the <body> tag, and you can set the value of this property from a script within the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

forms[]
An array of Form objects, one for each HTML form that appears in document. The forms[] array has forms.length elements, numbered from zero to forms.length-1.

images[] [ JavaScript 1.1]
An array of Image objects, one for each image that is embedded in the document with the HTML <img> tag. If the name attribute is specified in the <img> tag for an Image, a reference to that image is also stored in a property of the Document object. This property has the same name as the image. So if an image has a name="toggle" attribute, you can refer to the image with document.toggle.

lastModified
A read-only string that specifies the date of the most recent change to the document (as reported by the web server). See the Document.lastModified reference page.

linkColor
A string property that specifies the color of unvisited links in the document. The value of this property is set by the link attribute of the <body> tag, and it may also be set by a script in the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

links[]
An array of Link objects, one for each hypertext link that appears in the document. The links[] array has links.length elements, numbered from zero to links.length-1.

location [Deprecated]
A Location object that contains the complete URL of the current document; a synonym for the Window.location property. In JavaScript 1.0, this property was instead a read-only string object that served the same purpose as the Document.URL property.

plugins[] [ JavaScript 1.1]
A synonym for the embeds[] array. Refers to an array of objects that represent the plugins or ActiveX controls used to display embedded data in a document. The embeds property is the preferred way to access this array, since it avoids confusion with the Navigator.plugins[] array.

referrer
A read-only string property that contains the URL of the document, if any, from which the current document was reached. For example, if the user follows a link in document A to document B, the Document.referrer property in document B contains the URL of document A. On the other hand, if the user types the URL of document B directly and does not follow any link to get there, the Document.referrer property for document B is an empty string.

title
A read-only string property that specifies the title of the current document. The title is any text that appears between the <title> and </title> tags in the <head> of the document.

URL
A read-only string that specifies the URL of the document. See the Document.URL reference page.

vlinkColor
A string property that specifies the color of visited links in document. The value of this property is set by the vlink attribute of the <body> tag, and you can also set it from a script within the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

Netscape Properties

height [Netscape 4]
The height, in pixels, of the document.

layers[] [Netscape 4 only]
An array of Layer objects that represent the layers contained within a document. Each Layer object contains its own subdocument, accessible through the document property of the Layer object. This property is available only in Netscape 4; it has been discontinued in Netscape 6.

width [Netscape 4]
The width, in pixels, of the document.

Internet Explorer Properties

activeElement [IE 4]
A read-only property that refers to the input element within the document that is currently active (i.e., has the input focus).

all[] [IE 4]
An array of all elements within the document. See the Document.all[] reference page.

charset [IE 4]
The character set of the document.

children[] [IE 4]
An array that contains the HTML elements, in source order, that are direct children of the document. Note that this is different than the all[] array that contains all elements in the document, regardless of their position in the containment hierarchy.

defaultCharset [IE 4]
The default character set of the document.

expando [IE 4]
This property, if set to false, prevents client-side objects from being expanded. That is, it causes a runtime error if a program attempts to set the value of a nonexistent property of a client-side object. Setting expando to false can sometimes catch bugs caused by property misspellings, which can otherwise be difficult to detect. This property can be particularly helpful for programmers who are switching to JavaScript after becoming accustomed to case-insensitive languages. Although expando works only in IE 4, it can be set safely (if ineffectively) in Netscape.

parentWindow [IE 4]
The window that contains the document.

readyState
Specifies the loading status of a document. It has one of the following four string values:

uninitialized
The document has not started loading.

loading
The document is loading.

interactive
The document has loaded sufficiently for the user to interact with it.

complete
The document is completely loaded.

Methods

Document inherits methods from HTMLElement and defines the following methods. Netscape and IE both define a number of incompatible Document methods that are used mostly for DHTML; they are listed separately.

clear( )
Erases the contents of the document. This method is deprecated in JavaScript 1.1.

close( )
Closes a document stream opened with the open( ) method.

open( )
Opens a stream to which document contents may be written.

write( )
Inserts the specified string or strings into the document currently being parsed or into a document stream opened with open( ).

writeln( )
Identical to write( ), except that it appends a newline character to the output.

Netscape Methods

captureEvents( )
Requests events of specified types.

getSelection( )
Returns the currently selected document text.

releaseEvents
Stops capturing specified event types.

routeEvent( )
Routes a captured event to the next interested element. See Window.routeEvent( ).

Internet Explorer Methods

elementFromPoint( )
Returns the element located at a given (X-coordinate, Y-coordinate) point.

Event Handlers

The <body> tag has onload and onunload attributes. Technically, however, the onload and onunload event handlers belong to the Window object rather than the Document object. See Window.onload and Window.onunload.

HTML Syntax

The Document object obtains values for a number of its properties from attributes of the HTML <body> tag. Also, the HTML contents of a document appear between the <body> and </body> tags:

<body
  [ background="imageURL" ]  // A background image for the document
  [ bgcolor="color" ]        // A background color for the document
  [ text="color" ]           // The foreground color for the document's text
  [ link="color" ]           // The color for unvisited links
  [ alink="color" ]          // The color for activated links
  [ vlink="color" ]          // The color for visited links
  [ onload="handler" ]       // JavaScript to run when the document is loaded
  [ onunload="handler" ]     // JavaScript to run when the document is unloaded
>
// HTML document contents go here
</body>

Description

The Document object represents the HTML document displayed in a browser window or frame (or layer, in Netscape 4). The properties of this object provide details about many aspects of the document, from the colors of the text, background, and anchors, to the date on which the document was last modified. The Document object also contains a number of arrays that describe the contents of the document. The links[] array contains one Link object for each hypertext link in the document. Similarly, the applets[] array contains one object for each Java applet embedded in the document, and the forms[] array contains one Form object for each HTML form that appears in the document.

The write( ) method of the Document object is especially notable. When invoked in scripts that are run while the document is loading, you can call document.write( ) to insert dynamically generated HTML text into the document.

See Chapter 14 for an overview of the Document object and of many of the JavaScript objects to which it refers. See Chapter 17 for an overview of the DOM standard.

See Also

Form, the document property of the Window object; Chapter 14; Document, HTMLDocument, and HTMLBodyElement in the DOM reference section

Document.all[]all HTML elements in a document Internet Explorer 4

Synopsis

document.all[i] 
document.all[name]
document.all.tags(tagname)

Description

all[] is a versatile array that contains all the HTML elements in a document. all[] contains the elements in source order, and you can extract them directly from the array if you know their exact numeric position within the array. It is more common, however, to use the all[] array to retreive elements by the value of their name or id HTML attributes. If more than one element has the specified name, using that name as an index into the all[] returns an array of elements that share the name.

all.tags( ) is passed a tag name and returns an array of HTML elements of the specified type.

See Also

HTMLElement

Document.captureEvents( )see Window.captureEvents( )

Document.clear( )clear a document

Availability

JavaScript 1.0; deprecated

Synopsis

document.clear( ) 

Description

The clear( ) method of the Document object is deprecated and should not be used. To clear a document, you should simply open a new one with Document.open( ).

See Also

Document.close( ), Document.open( ), Document.write( )

Document.close( )close an output stream

Availability

JavaScript 1.0

Synopsis

document.close( ) 

Description

This method displays any output to document that has been written but not yet displayed and closes the output stream to document. When generating complete HTML pages with Document.write( ), you should invoke Document.close( ) when you reach the end of the page.

After document.close( ) has been called, if any further output is written to document (e.g., with document.write( )), the document is implicitly cleared and reopened, erasing all the output that was written prior to calling the close( ) method.

See Also

Document.open( ), Document.write( )

Document.cookiethe cookie(s) of the document

Availability

JavaScript 1.0

Synopsis

document.cookie 

Description

cookie is a string property that allows you to read, create, modify, and delete the cookie or cookies that apply to the current document. A cookie is a small amount of named data stored by the web browser. It gives web browsers a "memory" so they can use data input on one page in another page or recall user preferences across web browsing sessions. Cookie data is automatically transmitted between web browser and web server when appropriate so CGI scripts on the server end can read and write cookie values. Client-side JavaScript code can also read and write cookies with this property.

The Document.cookie property does not behave like a normal read/write property. You may both read and write the value of Document.cookie, but the value you read from this property is, in general, not the same as the value you write. For complete details on the use of this particularly complex property, see Chapter 16.

Usage

Cookies are intended for infrequent storage of small amounts of data. They are not intended as a general-purpose communication or programming mechanism, so use them in moderation. Note that web browsers are not required to retain the value of more than 20 cookies per web server (for the entire server, not just for your site on the server), nor to retain a cookie name/value pair of more than 4 KB in length.

See Also

Chapter 16

Document.domainthe security domain of a document

Availability

JavaScript 1.1

Synopsis

document.domain 

Description

For security reasons, an unsigned script running in one window is not allowed to read properties of another window unless that window comes from the same web server as the host. This causes problems for large web sites that use multiple servers. For example, a script on the host www.oreilly.com might want to share properties with a script from the host search.oreilly.com.

The domain property helps to address this problem. Initially, this string property contains the hostname of the web server from which the document was loaded. You can set this property, but only in a very restricted way: it can be set only to a domain suffix of itself. For example, a script loaded from search.oreilly.com could set its own domain property to "oreilly.com". If a script from www.oreilly.com is running in another window, and it also sets its domain property to "oreilly.com", these two scripts can share properties, even though they did not originate on the same server.

Note, however, that a script from search.oreilly.com cannot set its domain property to "search.oreilly". And, more importantly, a script from snoop.spam.com cannot set its domain to "oreilly.com", which might allow it to determine, for example, which search keywords you use.

See Also

Chapter 21

Document.elementFromPoint( )determine which HTML element is at a given point

Availability

Internet Explorer 4

Synopsis

document.elementFromPoint(x, y)

Arguments

x
The X-coordinate.

y
The Y-coordinate.

Returns

The HTML element that appears at point (x, y) in document.

Document.getSelection( )return the selected text Netscape 4

Synopsis

document.getSelection( )

Returns

The text, if any, that is currently selected within the document. This returned text has HTML formatting tags removed.

Document.handleEvent( )see Window.handleEvent( )

Document.lastModifiedthe modification date of a document

Availability

JavaScript 1.0

Synopsis

document.lastModified 

Description

lastModified is a read-only string property that contains the date and time at which document was most recently modified. This data is derived from HTTP header data sent by the web server. The web server generally obtains the last-modified date by examining the modification date of the file itself.

Web servers are not required to provide last-modified dates for the documents they serve. When a web server does not provide a last-modified date, JavaScript assumes 0, which translates to a date of midnight, January 1, 1970, GMT. The following example shows how you can test for this case.

Example

It is a good idea to let readers know how recent the information you provide on the Web is. You can include an automatic timestamp in your documents by placing the following script at the end of each HTML file. Doing this means you do not need to update the modification time by hand each time you make a change to the file. Note that this script tests that the supplied date is valid before displaying it:

<script>
if (Date.parse(document.lastModified) != 0)
    document.write('<p><hr><small><i>Last modified: '
                   + document.lastModified
                   + '</i></small>');
</script> 

See Also

The Document location, referrer, and title properties

Document.links[]the Link objects in a document

Availability

JavaScript 1.0

Synopsis

document.links 
document.links.length

Description

The links property is an array of Link objects -- one object for each hypertext link that appears in document. The links[] array has links.length elements, numbered from zero to links.length-1.

See Also

Link

Document.open( )begin a new document

Availability

JavaScript 1.0

Synopsis

document.open( ) 
document.open(mimetype)

Arguments

mimetype
An optional string argument that specifies the type of data to be written to and displayed in document. The value of this argument should be one of the standard MIME types that the browser understands ("text/html", "text/plain", "image/gif", "image/jpeg", and "image/x-bitmap" for Netscape) or some other MIME type that can be handled by an installed plugin. If this argument is omitted, it is taken to be "text/html". This argument is ignored by IE 3, which always assumes a document of type "text/html". This argument is also not supported in the standard W3C DOM version of this method. See the HTMLDocument.open( ) entry in the DOM reference section.

Description

The document.open( ) method opens a stream to document so subsequent document.write( ) calls can append data to the document. The optional mimetype argument specifies the type of data to be written and tells the browser how to interpret that data.

If any existing document is displayed when the open( ) method is called, it is automatically cleared by the call to open( ) or by the first call to write( ) or writeln( ). After opening a document with open( ) and writing data to it with write( ), you should complete the document by calling close( ).

Usage

You usually call Document.open( ) with no argument to open an HTML document. Occasionally, a "text/plain" document is useful, for example, for a pop-up window of debugging messages.

See Also

Document.close( ), Document.write( ); HTMLDocument.open( ) in the DOM reference section

Document.releaseEvents( )see Window.releaseEvents( )

Document.routeEvent( )see Window.routeEvent( )

Document.URLthe URL of the current document

Availability

JavaScript 1.1

Synopsis

document.URL 

Description

URL is a read-only string property that contains the complete URL of the current document.

document.URL is usually equal to window.location.href for the window that contains document. These two are not always equal, however, because the Document.URL property may be modified through URL redirection -- Window.location contains the requested URL, and Document.URL specifies the actual URL where it was found.

Usage

Some web authors like to include the URL of a document somewhere within the document so, for example, if the document is cut-and-pasted to a file or printed out, there is still a reference to its location online. The following script, when appended to a document, automatically adds the document's URL:

<script>
document.write('<p><hr><small><i>URL: ' + document.URL
    + '</i></small>');
</script>

See Also

The lastModified, location, referrer, and title properties of the Document object; the location property of the Window object

Document.write( )append data to a document

Availability

JavaScript 1.0

Synopsis

document.write(value, ...)

Arguments

value
An arbitrary JavaScript value to be appended to document. If the value is not a string, it is converted to one before being appended.

...
Any number (zero or higher) of additional values to be appended (in order) to document.

Description

document.write( ) appends each of its arguments, in order, to document. Any arguments that are not strings are converted to strings before they are written to the end of the document.

Document.write( ) is usually used in one of two ways. First, it can be invoked on the current document within a <script> tag or within a function that is executed while the document is being parsed. In this case, the write( ) method writes its HTML output as if that output appeared literally in the file at the location of the code that invoked the method.

Second, you can use Document.write( ) to dynamically generate the contents of a document for a window other than the current window. In this case, the target document is never in the process of being parsed, and so the output cannot appear "in place" as it does in the case just described. In order for write( ) to output text into a document, that document must be open. You can open a document by explicitly calling the Document.open( ) method. In most cases this is unnecessary, however, because when write( ) is invoked on a document that is closed, it implicitly opens the document. When a document is opened, any contents that previously appeared in that document are discarded and replaced with a blank document.

Once a document is open, Document.write( ) can append any amount of output to the end of the document. When a new document has been completely generated by this technique, the document should be closed by calling Document.close( ). Note that although the call to open( ) is usually optional, the call to close( ) is never optional.

The results of calling Document.write( ) may not be immediately visible in the targeted web browser window or frame. This is because a web browser may buffer up data to output in larger chunks. Calling Document.close( ) is the only way to explicitly force all buffered output to be "flushed" and displayed in the browser window.

See Also

Document.close( ), Document.open( ), Document.writeln( ); Chapter 14

Document.writeln( )append data and a newline to a document

Availability

JavaScript 1.0

Synopsis

document.writeln(value, ...)

Arguments

value
An arbitrary JavaScript value to be appended to document. If the value is not a string, it is converted to one before being appended.

...
Any number (zero or higher) of additional values to be appended (in order) to document.

Description

Document.writeln( ) behaves just like Document.write( ) except that after appending all of its arguments to document, it also appends a newline character. See the Document.write( ) reference page for more information on this method.

Newline characters are not usually displayed in HTML documents, so Document.writeln( ) is generally useful only when writing text to appear in a <pre> environment, or when writing to a document opened with a MIME type of "text/plain".

See Also

Document.close( ), Document.open( ), Document.write( )

Elementsee Input

Eventdetails about an event

Availability

JavaScript 1.2; incompatible versions supported by Netscape 4 and IE 4

Synopsis

function handler(event) { ... } // Event handler argument in Netscape 4 
window.event   // Window property in IE 4

Constants

In Netscape 4, the Event object defines bitmask constants for each of the supported event types. These static properties are used to form the bitmasks that are passed to captureEvents( ) and releaseEvents( ). The available constants are:

Event.ABORT
Event.BLUR
Event.CHANGE
Event.CLICK
Event.DBLCLICK
Event.DRAGDROP
Event.ERROR
Event.FOCUS
Event.KEYDOWN
Event.KEYPRESS
Event.KEYUP
Event.LOAD
Event.MOUSEDOWN
Event.MOUSEMOVE
Event.MOUSEOUT
Event.MOUSEOVER
Event.MOUSEUP
Event.MOVE
Event.RESET
Event.RESIZE
Event.SELECT
Event.SUBMIT
Event.UNLOAD

Netscape 4 Properties

height
Set only in events of type "resize". Specifies the new height of the window or frame that was resized.

layerX, layerY
Specify the X- and Y-coordinates, relative to the enclosing layer, at which an event occurred.

modifiers
Specifies which keyboard modifier keys were held down when the event occurred. This numeric value is a bitmask consisting of any of the constants Event.ALT_MASK, Event.CONTROL_MASK, Event.META_MASK, or Event.SHIFT_MASK. Due to a bug, this property is not defined in Netscape 6 or 6.1.

pageX, pageY
Specify the X- and Y-coordinates, relative to the web browser page, at which the event occurred. Note that these coordinates are relative to the top-level page, not to any enclosing layers.

screenX, screenY
Specify the X- and Y-coordinates, relative to the screen, at which the event occurred. Note that, unlike most Event properties, these properties are supported by and have the same meaning in both Netscape 4 and Internet Explorer 4.

target
Specifies the Window, Document, Layer, or HTMLElement object on which the event occurred.

type
A string property that specifies the type of the event. Its value is the name of the event handler minus the "on" prefix. So when the onclick( ) event handler is invoked, the type property of the Event object is "click".

which
For keyboard and mouse events, which specifies which key or mouse button was pressed or released. For keyboard events, this property contains the character encoding of the key that was pressed. For mouse events, it contains 1, 2, or 3, indicating the left, middle, or right buttons.

width
Set only in events of type "resize". Specifies the new width of the window or frame that was resized.

x, y
Specify the X- and Y-coordinates at which the event occurred. In Netscape 4, these properties are synonyms for layerX and layerY and specify the position relative to the containing layer (if any). Their meaning is different in Internet Explorer (see below).

Internet Explorer 4 Properties

altKey
A boolean value that specifies whether the Alt key was held down when the event occurred.

button
For mouse events, button specifies which mouse button or buttons were pressed. This read-only integer is a bitmask: the 1 bit is set if the left button was pressed; the 2 bit is set if the right button was pressed; and the 4 bit is set if the middle button (of a three-button mouse) was pressed.

cancelBubble
If an event handler wants to stop an event from being propagated up to containing objects, it must set this property to true.

clientX, clientY
Specify the X- and Y-coordinates, relative to the web browser page, at which the event occurred.

ctrlKey
A boolean value that specifies whether the Ctrl key was held down when the event occurred.

fromElement
For mouseover and mouseout events, fromElement refers to the object from which the mouse pointer is moving.

keyCode
For keyboard events, keyCode specifies the Unicode character code generated by the key that was struck.

offsetX, offsetY
Specify the X- and Y-coordinates at which the event occurred within the coordinate system of the event's source element (see srcElement).

reason
For the datasetcomplete event, reason contains a code that specifies the status of the data transfer. A value of 0 indicates a successful transfer. A value of 1 indicates that the transfer was aborted. A value of 2 indicates that an error occurred during data transfer.

returnValue
If this property is set, its value takes precedence over the value actually returned by an event handler. Set this property to false to cancel the default action of the source element on which the event occurred.

screenX, screenY
Specify the X- and Y-coordinates, relative to the screen, at which the event occurred. Note that, unlike most Event properties, these two properties are supported by and have the same meaning in both Netscape 4 and Internet Explorer 4.

shiftKey
A boolean value that specifies whether the Shift key was held down when the event occurred.

srcElement
A reference to the Window, Document, or HTMLElement object that generated the event.

srcFilter
For filterchange events, srcFilter specifies the filter that changed.

toElement
For mouseover and mouseout events, toElement refers to the object into which the mouse pointer is moving.

type
A string property that specifies the type of the event. Its value is the name of the event handler minus the "on" prefix. So when the onclick( ) event handler is invoked, the type property of the Event object is "click".

x, y
Specify the X- and Y-coordinates at which the event occurred. In Internet Explorer 4, this property specifies the X position relative to the innermost containing element that is dynamically positioned using CSS. The interpretation of these properties is different in Netscape 4 (see the previous section).

Description

The Event object provides details about an event that has occurred. Unfortunately, these details are not standardized, and Netscape 4 and IE 4 define Event objects that are almost entirely incompatible. Besides having different properties, Netscape 4 and IE 4 provide access to Event objects in different ways. In Netscape, an Event object is passed as an argument to every event handler. For event handlers defined by HTML attributes, the name of the event argument is event. In IE, the Event object of the most recent event is instead stored in the event property of the Window object.

In addition to the incompatibility between the Netscape 4 Event object and the IE Event object, the W3C DOM defines its own Event object that is incompatible with both. See the Event, UIEvent, and MouseEvent entries in the DOM reference section.

See Also

Chapter 19; Event, UIEvent, and MouseEvent in the DOM reference section

FileUploada file upload field for form input

Availability

JavaScript 1.0 Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i]

Properties

FileUpload inherits properties from Input and HTMLElement and defines or overrides the following:

value [ JavaScript 1.1]
A read-only string that specifies the filename entered by the user into the FileUpload object. The user may enter a filename either by typing it directly or by using the directory browser associated with the FileUpload object.

To prevent malicious programs from uploading arbitrary files from the client, this property may not be set by JavaScript code. Similarly, the value attribute of the <input> tag does not specify the initial value for this property.

Methods

FileUpload inherits methods from Input and HTMLElement.

Event Handlers

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

onchange
Invoked when the user changes the value in the FileUpload element and moves the keyboard focus elsewhere. This event handler is not invoked for every keystroke in the FileUpload element, but only when the user completes an edit.

HTML Syntax

A FileUpload element is created with a standard HTML <input> tag:

<form enctype="multipart/form-data"
      method="post">         // Required attributes
    ...
  <input
    type="file"              // Specifies that this is a FileUpload element
    [ name="name" ]          // A name you can use later to refer to this element
                             // Specifies the name property
    [ size="integer" ]       // How many characters wide the element is
    [ maxlength="integer" ]  // Maximum allowed number of input characters
    [ onblur="handler" ]     // The onblur( ) event handler
    [ onchange="handler" ]   // The onchange( ) event handler
    [ onfocus="handler" ]    // The onfocus( ) event handler
  >
    ...

Description

The FileUpload element represents a file upload input element in a form. In many respects, this input element is much like the Text element. On the screen, it appears like a text input field with the addition of a Browse button that opens a directory browser. Entering a filename into a FileUpload element (either directly or through the browser) causes Netscape to submit the contents of that file along with the form. For this to work, the form must use "multipart/form-data" encoding and the POST method.

The FileUpload element does not have a defaultValue property and does not recognize the value HTML attribute to specify an initial value for the input field. Similarly, the value property of the FileUpload element is read-only. Only the user may enter a filename; JavaScript may not enter text into the FileUpload field in any way. This is to prevent malicious JavaScript programs from uploading arbitrary files (such as password files) from the user's machine.

See Also

Form, HTMLElement, Input, Text; HTMLInputElement in the DOM reference section

FileUpload.onchangethe handler invoked when input value changes

Available

JavaScript 1.0

Synopsis

<input type="file" onchange="handler"...> 
fileupload.onchange

Description

The onchange property of a FileUpload element specifies an event handler function that is invoked when the user changes the value in the input field (either by typing directly or using the Browse button) and then moves input focus elsewhere. This handler is intended to process a complete change to the input value and therefore is not invoked on a keystroke-by-keystroke basis.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onchange attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onchange handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

Input.onchange; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Forman HTML input form

Availability

JavaScript 1.0 Inherits from HTMLElement

Synopsis

document.form_name 
document.forms[form_number]

Properties

Form inherits properties from HTMLElement and defines or overrides the following:

action
A read/write string (read-only in IE 3) that specifies the URL to which the form data is sent when the form is submitted. The initial value of this property is specified by the action attribute of the <form> HTML tag. Usually, this URL specifies the address as a CGI script, although it can also be a mailto: or news: address.

elements[]
An array of input elements that appear in the form. Each element is a Button, Checkbox, Hidden, Password, Radio, Reset, Select, Submit, Text, or Textarea object. See the Form.elements[] reference page.

encoding
A read/write string (read-only in IE 3) that specifies how form data is encoded for transmission when the form is submitted. The initial value of this property is specified by the enctype attribute of the <form> tag. The default value is "application/x-www-form-urlencoded", which is sufficient for almost all purposes. Other values may sometimes be necessary. For example, a value of "text/plain" is convenient when the form is submitted by email to a mailto: URL. See CGI Programming on the World Wide Web, by Shishir Gundavaram (O'Reilly), for further information.

length
The number of elements in the form. Equivalent to elements.length.

method
A read/write string (read-only in IE 3) that specifies the method by which form data is submitted. The initial value of this property is specified by the method attribute of the <form> tag. The two legal values are get and post.

The get method is the default. It is usually used for form submissions such as database queries that do not have side effects. With this method, the encoded form data is appended to the URL specified by the Form.action property. The post method is appropriate for form submissions, such as additions to databases, that have side effects. With this method, encoded form data is sent in the body of the HTTP request.

name
Specifies the name of the form. The initial value of this read/write string property is the value of the name attribute of the <form> tag.

target
A read/write string that specifies the name of the frame or window in which the results of submitting a form should be displayed. Initially specified by the target attribute. The special names "_top", "_parent", "_self", and "_blank" are also supported for the target property and the target attribute. See the Form.target reference page.

Methods

Form inherits methods from HTMLElement and defines the following:

reset( )
Resets each of the input elements of the form to their default values.

submit( )
Submits the form.

Event Handlers

Form inherits event handlers from HTMLElement and defines the following:

onreset
Invoked just before the elements of the form are reset. Specified in HTML by the onreset attribute.

onsubmit
Invoked just before the form is submitted. Specified in HTML by the onsubmit attribute. This event handler allows form entries to be validated before being submitted.

HTML Syntax

A Form object is created with a standard HTML <form> tag. The form contains any input elements created with the <input>, <select>, and <textarea> tags between <form> and </form>:

<form
    [ name="form_name" ]       // Used to name the form in JavaScript
    [ target="window_name" ]   // The name of the window for responses
    [ action="url" ]           // The URL to which the form is submitted
    [ method=("get"|"post") ]  // The method of form submission
    [ enctype="encoding" ]     // How the form data is encoded
    [ onreset="handler" ]      // A handler invoked when form is reset
    [ onsubmit="handler" ]     // A handler invoked when form is submitted
>
// Form text and input elements go here
</form> 

Description

The Form object represents an HTML <form> in a document. Each form in a document is represented as an element of the Document.forms[] array. Named forms are also represented by the form_name property of their document, where form_name is the name specified in the name attribute of the <form> tag.

The elements of a form (buttons, input fields, checkboxes, and so on) are collected in the Form.elements[] array. Named elements, like named forms, can also be referenced directly by name -- the element name is used as a property name of the Form object. Thus, to refer to a Text object element named phone within a form named questionnaire, you might use the JavaScript expression:

document.questionnaire.phone

See Also

Button, Checkbox, FileUpload, Hidden, Input, Password, Radio, Reset, Select, Submit, Text, Textarea; Chapter 15; HTMLFormElement in the DOM reference section

Form.elements[]the input elements of the form

Availability

JavaScript 1.0

Synopsis

form.elements[i] 
form.elements.length

Description

form.elements[] is an array of the form input objects in form. The array has elements.length items in it. These items may be of any of the form input element types: Button, Checkbox, Hidden, Password, Radio, Reset, Select, Submit, Text, and Textarea. These form input objects appear in the array in the same order that they appear in the HTML source code for the form.

Usage

If an item in the form.elements[] array has been given a name with the name="name" attribute of its HTML <input> tag, that item's name becomes a property of form, and this property refers to the item. Thus, it is possible to refer to input objects by name instead of by number:

form.name 

Referring to elements by name is usually easier, so it is a good idea to specify the name attribute for all form elements.

See Also

Button, Checkbox, Form, Hidden, Input, Password, Radio, Reset, Select, Submit, Text, Textarea

Form.onresetthe handler invoked when a form is reset

Availability

JavaScript 1.1

Synopsis

<form ... onreset="handler" ... >
form.onreset

Description

The onreset property of a Form object specifies an event handler function that is invoked when the user clicks on a Reset button in the form or when Form.reset( ) is called.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onreset attribute of the HTML <form> tag. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than the scope of the containing window.

In the Netscape 4 event model, the onreset handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

If the onreset handler returns false, the elements of the form are not reset.

Example

You could use the following event handler to ask the user to confirm that they really want to reset the form:

<form ...
    onreset="return confirm('Really erase all entered data?')"
> 

See Also

Form.onsubmit, Form.reset( ); Chapter 19; Section , EventListener, and EventTarget in the DOM reference section

Form.onsubmitinvoked when a form is submitted

Availability

JavaScript 1.0

Synopsis

<form ... onsubmit="handler" ... >
form.onsubmit

Description

The onsubmit property of a Form object specifies an event handler function that is invoked when the user submits a form by clicking on a Submit button in the form. Note that this event handler is not invoked when the Form.submit( ) method is called.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onsubmit attribute of the HTML <form> tag. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than the scope of the containing window.

In the Netscape 4 event model, the onsubmit handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

If the onsubmit handler returns false, the elements of the form are not submitted. If the handler returns any other value or returns nothing, the form is submitted normally. Because the onsubmit handler can cancel form submission, it is ideal for performing form data validation.

See Also

Form.onreset, Form.submit( ); Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Form.reset( )reset the elements of a form

Availability

JavaScript 1.1

Synopsis

form.reset( ) 

Description

The reset( ) method resets the specified form, restoring each element of the form to its default value, exactly as if a Reset button had been pressed by the user. The form's onreset( ) event handler is first invoked and may prevent the reset from occurring by returning the value false.

Form.submit( )submit a formJavaScript 1.0

Availability

Synopsis

form.submit( ) 

Description

The submit( ) method submits the specified form, almost as if a Submit button had been pressed by the user. The form is submitted as specified by the action, method, and encoding properties of form (or the action, method, and enctype attributes of the <form> tag), and the results are displayed in the window or frame specified by the target property or the target attribute.

The one important difference between the submit( ) method and form submission by the user is that the onsubmit( ) event handler is not invoked when submit( ) is called. If you use onsubmit( ) to perform input validation, for example, you'll have to do that validation explicitly before calling submit( ).

Usage

It is more common to use a Submit button that allows the user to submit the form than to call the submit( ) method yourself.

Form.targetthe window for form results

Availability

JavaScript 1.0;

Inherits from/Overrides

read-only in Internet Explorer 3

Synopsis

form.target

Description

target is a read/write string property of the Form object. It specifies the name of the frame or window in which the results of the submission of form should be displayed. The initial value of this property is specified by the target attribute of the <form> tag. If unset, the default is that form submission results appear in the same window as the form.

Note that the value of target is the name of a frame or window, not the actual frame or window itself. The name of a frame is specified by the name attribute of the <frame> tag. The name of a window is specified when the window is created with a call to the Window.open( ) method. If target specifies the name of a window that does not exist, the browser automatically opens a new window to display the results of form submission, and any future forms with the same target name use the same newly created window.

Four special target names are supported. The target named "_blank" specifies that a new, empty browser window should be created and used to display the results of the form submission. The target "_self" is the default; it specifies that the form submission results should be displayed in the same frame or window as the form itself. The target "_parent" specifies that the results should be displayed in the parent frame of the frame that contains the form. Finally, the "_top" target specifies that the results should be displayed in the topmost frame -- in other words, all frames should be removed, and the results should occupy the entire browser window.

You can set this property in IE 3, but doing so has no effect on the actual target of the form.

See Also

Link.target

Framea type of Window object

Availability

JavaScript 1.0

Synopsis

window.frames[i] 
window.frames.length
frames[i] 
frames.length

Description

Though the Frame object is sometimes referred to, there is, strictly speaking, no such object. All frames within a browser window are instances of the Window object, and they contain the same properties and support the same methods and event handlers as the Window object. See the Window object and its properties, methods, and event handlers for details.

There are a few practical differences between Window objects that represent top-level browser windows and those that represent frames within a browser window, however:

See Also

Window

getClass( )return the JavaClass of a JavaObject

Availability

Netscape 3 LiveConnect

Synopsis

getClass(javaobj) 

Arguments

javaobj
A JavaObject object.

Returns

The JavaClass object of javaobj.

Description

getClass( ) is a function that takes a JavaObject object ( javaobj) as an argument. It returns the JavaClass object of that JavaObject. That is, it returns the JavaClass object that represents the Java class of the Java object represented by the specified JavaObject.

Usage

Don't confuse the JavaScript getClass( ) function with the getClass method of all Java objects. Similarly, don't confuse the JavaScript JavaClass object with the Java java.lang.Class class.

Consider the Java Rectangle object created with the following line:

var r = new java.awt.Rectangle( );

r is a JavaScript variable that holds a JavaObject object. Calling the JavaScript function getClass( ) returns a JavaClass object that represents the java.awt.Rectangle class:

var c = getClass(r); 

You can see this by comparing this JavaClass object to java.awt.Rectangle:

if (c == java.awt.Rectangle) ... 

The Java getClass( ) method is invoked differently and performs an entirely different function:

c = r.getClass( ); 

After executing the above line of code, c is a JavaObject that represents a java.lang.Class object. This java.lang.Class object is a Java object that is a Java representation of the java.awt.Rectangle class. See your Java documentation for details on what you can do with the java.lang.Class class.

To summarize, you can see that the following expression always evaluates to true for any JavaObject o:

(getClass(o.getClass( )) == java.lang.Class) 

See Also

JavaArray, JavaClass, JavaObject, JavaPackage, the java property of the Window object; Chapter 22

Hiddenhidden data for client/server communication

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i]

Properties

Hidden inherits properties from Input and HTMLElement and defines or overrides the following:

value
A read/write string that specifies arbitrary data passed to the web server when the form containing the Hidden object is submitted. The initial value of value is specified by the value attribute of the <input> tag that defines the Hidden object.

HTML Syntax

A Hidden element is created with a standard HTML <input> tag:

<form>
    ...
  <input
    type="hidden"      // Specifies that this is a Hidden element
    [ name="name" ]    // A name you can use later to refer to this element
                       // Specifies the name property
    [ value="value" ]  // The value transmitted when the form is submitted
                       // Specifies the initial value of the value property
  >
    ...
</form> 

Description

The Hidden element is an invisible form element that allows arbitrary data to be transmitted to the server when the form is submitted. You can use a Hidden element when you want to transmit information other than the user's input data to the server.

When an HTML document is generated on the fly by a server, another use of Hidden form elements is to transmit data from the server to the client for later processing by JavaScript on the user's side. For example, the server might transmit raw data to the client in a compact, machine-readable form by specifying the data in the value attribute of a Hidden element or elements. On the client side, a JavaScript program (transmitted along with the data or in another frame) could read the value property of the Hidden element or elements and process, format, and display that data in a less compact, human-readable (and perhaps user-configurable) format.

Hidden elements can also be useful for communication between CGI scripts, even without the intervention of JavaScript on the client side. In this usage, one CGI script generates a dynamic HTML page containing hidden data, which is then submitted to a second CGI script. This hidden data can communicate state information, such as the results of the submission of a previous form.

Cookies can also be used to transmit data from client to server. An important difference between Hidden form elements and cookies, however, is that cookies are persistent on the client side.

See Also

Document.cookie, Form, HTMLElement, Input; HTMLInputElement in the DOM reference section

Historythe URL history of the browser

Availability

JavaScript 1.0

Synopsis

window.history 
frame.history 
history

Properties

length
This numeric property specifies the number of URLs in the browser's history list. Since there is no way to determine the index of the currently displayed document within this list, knowing the size of this list is not particularly helpful.

Methods

back( )
Goes backward to a previously visited URL.

forward( )
Goes forward to a previously visited URL.

go( )
Goes to a previously visited URL.

Description

The History object represents the browsing history of a window -- it maintains a list of recently visited web pages. For security and privacy reasons, however, the contents of this list are not accessible to scripts. Although scripts cannot access the URLs represented by the History object, they can use the length property to determine the number of URLs in the list and the back( ), forward( ), and go( ) methods to cause the browser to revisit any of the URLs in the array.

Example

The following line performs the same action as clicking a browser's Back button:

history.back( ); 

The following performs the same action as clicking the Back button twice:

history.go(-2); 

See Also

The history property of the Window object, Location

History.back( )return to the previous URL

Availability

JavaScript 1.0

Synopsis

history.back( ) 

Description

back( ) causes the window or frame to which the History object belongs to revisit the URL (if any) that was visited immediately before the current one. Calling this method has the same effect as clicking on the browser's Back button. It is also equivalent to:

history.go(-1); 
History.forward( )visit the next URL

Availability

JavaScript 1.0

Synopsis

history.forward( ) 

Description

forward( ) causes the window or frame to which the History object belongs to revisit the URL (if any) that was visited immediately after the current one. Calling this method has the same effect as clicking on the browser's Forward button. It is also equivalent to:

history.go(1); 

Note that if the user has not used the Back button or the Go menu to move backward through the history, and if JavaScript has not invoked the History.back( ) or History.go( ) methods, the forward( ) method has no effect because the browser is already at the end of its list of URLs, and there is no URL to go forward to.

History.go( )revisit a URL

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

history.go(relative_position)
history.go(target_string)

Arguments

relative_position
The relative position in the History list of the URL to be visited. In IE 3, this argument must be 1, 0, or -1.

target_string
A substring of the URL to be visited. This version of the go( ) method was added in JavaScript 1.1.

Description

The first form of the History.go( ) method takes an integer argument and causes the browser to visit the URL that is the specified number of positions distant in the history list maintained by the History object. Positive arguments move the browser forward through the list, and negative arguments move it backward. Thus, calling history.go(-1) is equivalent to calling history.back( ) and produces the same effect as clicking on the Back button. Similarly, history.go(3) revisits the same URL that would be visited by calling history.forward( ) three times. Calling go( ) with an argument of 0 causes the current page to be reloaded (although in Netscape 3, the Location.reload( ) provides a better way of doing this). This form of the method is buggy in multiframe documents in Netscape 3, and in Internet Explorer it can be called only with the values 1, 0, and -1.

The second form of the History.go( ) method was implemented in JavaScript 1.1. It takes a string argument and causes the browser to revisit the first (i.e., most recently visited) URL that contains the specified string.

HTMLElementthe superclass of all HTML elements

Availability

JavaScript 1.2

Synopsis

HTMLElement is the superclass of all classes that represent HTML elements. Therefore, HTMLElement objects are used in many contexts in client-side JavaScript and are available in all of the following ways:

document.images[i]
document.links[i]
document.anchors[i]
document.forms[i]
document.forms[i].elements[j]
document.elementName
document.formName.elementName
document.all[i]

Properties

all[] [IE 4]
The complete list of elements contained within this element, in source order. This property behaves exactly like the Document.all[] property. See the Document.all[] reference page.

children[] [IE 4]
The elements that are direct children of this element.

className [IE 4, Netscape 6]
A read/write string that specifies the value of the class attribute of an element. This property is used in conjunction with Cascading Style Sheets.

document [IE 4]
A reference to the containing Document object.

id [IE 4, Netscape 6]
A read/write string that specifies the value of the id attribute of an element. This property is used to assign a unique name to an element.

innerHTML [IE 4, Netscape 6]
A read/write string that specifies the HTML text that is contained within the element, not including the opening and closing tags of the element itself. Setting this property replaces the content of the element with the specified HTML text. Note that you cannot set this property while the document is loading.

innerText [IE 4]
A read/write string that specifies the plain text contained within the element, not including the opening and closing tags of the element itself. Setting this property replaces the content of the element with unparsed plain text. Note that you cannot set this property while the document is loading.

lang [IE 4, Netscape 6]
A read/write string that specifies the value of the lang HTML attribute of the element.

offsetHeight [IE 4]
The height, in pixels, of the element and all its content.

offsetLeft [IE 4]
The X-coordinate of the element relative to the offsetParent container element.

offsetParent [IE 4]
Specifies the container element that defines the coordinate system in which offsetLeft and offsetTop are measured. For most elements, offsetParent is the Document object that contains them. However, if an element has a dynamically positioned container, the dynamically positioned element is the offsetParent. Similarly, table cells are positioned relative to the row in which they are contained.

offsetTop [IE 4]
The Y-coordinate of the element, relative to the offsetParent container element.

offsetWidth [IE 4]
The width, in pixels, of the element and all its content.

outerHTML [IE 4]
A read/write property that specifies the HTML text of an element, including its start and end tags. Setting this property to a string of HTML text completely replaces element and its contents. Note that you cannot set this property while the document is loading.

outerText [IE 4]
A read/write property that specifies the plain text of an element, including its start and end tags. Setting this property completely replaces element and its contents with the specified plain text. Note that you cannot set this property while the document is loading.

parentElement [IE 4]
The element that is the direct parent of this element. This property is read-only.

sourceIndex [IE 4]
The index of the element in the Document.all[] array of the document that contains it.

style [IE 4, Netscape 6]
The inline CSS style attributes for this element. Setting properties of this Style object changes the display style of the element. See Chapter 18.

tagName [IE 4, Netscape 6]
A read-only string that specifies the name of the HTML tag that defined element.

title [IE 4, Netscape 6]
A read/write string that specifies the value of the title attribute of the HTML tag that defined element. Most browsers use this string as a "tool tip" for the element.

Methods

contains( )
Determines whether the element contains a specified element.

getAttribute( )
Gets the value of a named attribute.

handleEvent( )
Passes an Event object to the appropriate event handler.

insertAdjacentHTML( )
Inserts HTML text into the document near this element.

insertAdjacentText( )
Inserts plain text into the document near this element.

removeAttribute( )
Deletes an attribute and its value from the element.

scrollIntoView( )
Scrolls the document so the element is visible at the top or bottom of the window.

setAttribute( )
Sets the value of an attribute of the element.

Event Handlers

onclick
Invoked when the user clicks on the element.

ondblclick
Invoked when the user double-clicks on the element.

onhelp
Invoked when the user requests help. IE 4 only.

onkeydown
Invoked when the user presses a key.

onkeypress
Invoked when the user presses and releases a key.

onkeyup
Invoked when the user releases a key.

onmousedown
Invoked when the user presses a mouse button.

onmousemove
Invoked when the user moves the mouse.

onmouseout
Invoked when the user moves the mouse off the element.

onmouseover
Invoked when the user moves the mouse over an element.

onmouseup
Invoked when the user releases a mouse button.

Description

HTMLElement is the superclass of all JavaScript classes that represent HTML elements: Anchor, Form, Image, Input, Link, and so on. HTMLElement defines event handlers that are implemented by all elements in both IE 4 and Netscape 4. Because The IE 4 document object model exposes all HTML elements in a document, it defines quite a few properties and methods for those elements. Netscape 4 implements none of these IE properties and methods (except handleEvent( ), which is Netscape-specific), but Netscape 6 implements those that have been standardized by the W3C DOM. See the Chapter 25 reference section for complete information on the standard properties and methods of HTML elements.

See Also

Anchor, Form, Image, Input, Link; Chapter 17; Chapter 19; Element, HTMLElement, and Node in the DOM reference section

HTMLElement.contains( )whether one element is contained in another

Availability

Internet Explorer 4

Synopsis

element.contains(target)

Arguments

target
An HTMLElement object.

Returns

true if element contains target; false if it does not.

HTMLElement.getAttribute( )get an attribute value

Availability

Internet Explorer 4, Netscape 6

Synopsis

element.getAttribute(name)

Arguments

name
The name of the attribute.

Returns

The value of the named attribute of element or null if element does not have an attribute named name.

HTMLElement.handleEvent( )see Window.handleEvent( )

HTMLElement.insertAdjacentHTML( )insert HTML text around an element

Availability

Internet Explorer 4

Synopsis

element.insertAdjacentHTML(where, text)

Arguments

where
A string specifying where the text is to be inserted. The value "BeforeBegin" specifies that text is to be inserted before the start tag of element. "AfterBegin" specifies that text is to be inserted immediately after the start tag of element. "BeforeEnd" specifies that text is to be inserted immediately before the end tag of element. "AfterEnd" specifies that text is to be inserted immediately after the end tag of element.

text
The HTML text to insert.

Description

insertAdjacentHTML( ) inserts the HTML text at a position within or next to element, as specified by the argument where.

HTMLElement.insertAdjacentText( )insert plain text before or after an element

Availability

Internet Explorer 4

Synopsis

element.insertAdjacentText(where, text)

Arguments

where
A string that specifies where the text is to be inserted. The value "BeforeBegin" specifies that text is to be inserted before the start tag of element. "AfterBegin" specifies that text is to be inserted immediately after the start tag of element. "BeforeEnd" specifies that text is to be inserted immediately before the end tag of element. "AfterEnd" specifies that text is to be inserted immediately after the end tag of element.

text
The plain text to insert.

Description

insertAdjacentText( ) inserts the plain text text at a position within or next to element, as specified by the argument where.

HTMLElement.onclickthe handler invoked when the user clicks on an element

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onclick="handler" ... > 
element.onclick

Description

The onclick property of an HTMLElement object specifies an event handler function that is invoked when the user clicks on the element. Note that onclick is different than onmousedown. A click event does not occur unless a mousedown event and the subsequent mouseup event both occur over the same element.

The initial value of this property is a function that contains the JavaScript statements specified by the onclick attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onclick handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

In Netscape 4, the Event.which property specifies which mouse button was pressed. In IE 4, the Event.button property specifies the button number.

See Also

Event, Input.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

HTMLElement.ondblclickthe handler invoked when the user double-clicks on an element

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element ondblclick="handler" ... > 
element.ondblclick

Description

The ondblclick property of an HTMLElement object specifies an event handler function that is invoked when the user double-clicks on the element.

The initial value of this property is a function that contains the JavaScript statements specified by the ondblclick attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the ondblclick handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

Event; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

HTMLElement.onhelpthe handler invoked when the user presses F1

Availability

Internet Explorer 4

Synopsis

<element onhelp="handler" ... > 
element.onhelp

Description

The onhelp property of element specifies an event handler function that is invoked when the user presses the F1 key while element has keyboard focus.

The initial value of this property is a function that contains the JavaScript statements specified by the onhelp attribute of the HTML tag that defined the element. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

After the onhelp handler function is invoked, Internet Explorer 4 displays the built-in help window.

HTMLElement.onkeydownthe handler invoked when the user presses a key

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onkeydown="handler" ... > 
element.onkeydown

Description

The onkeydown property of an HTMLElement object specifies an event handler function that is invoked when the user presses a key over the element.

The initial value of this property is a function that contains the JavaScript statements specified by the onkeydown attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onkeydown handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

The character code of the key pressed is contained in the which property of the Event object in Netscape and in the keyCode property of the Event object in IE. You can convert this keycode to a string with String.fromCharCode( ). The modifier keys in effect can be determined from the Event.modifiers property in Netscape or with Event.shiftKey( ) and related methods in IE.

In the Netscape event model, you can cancel processing of the keystroke by returning false from this handler. In the IE event model, you cancel processing by setting Event.returnValue to false. In IE, this handler may return an alternate keycode that is used in place of the key actually pressed by the user.

You can often use the onkeypress event handler instead of the onkeydown and onkeyup handlers.

See Also

Event, HTMLElement.onkeypress; Chapter 19

HTMLElement.onkeypressthe handler invoked when the user presses a key

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onkeypress="handler" ... > 
element.onkeypress

Description

The onkeypress property of an HTMLElement object specifies an event handler function that is invoked when the user presses a key over the element. A keypress event is generated after a key down event and before the corresponding key up event. The keypress and key down events are similar. Unless you care about receiving individual key up events, you should use onkeypress instead of onkeydown.

The initial value of this property is a function that contains the JavaScript statements specified by the onkeypress attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onkeypress handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

The character code of the key pressed is contained in the which property of the Event object in Netscape and in the keyCode property of the Event object in IE. You can convert this keycode to a string with String.fromCharCode( ). The modifier keys in effect can be determined from the Event.modifiers property in Netscape or with Event.shiftKey( ) and related methods in IE.

In Netscape, you can cancel processing of the keystroke by returning false from this handler. In IE, you cancel processing by setting Event.returnValue to false. In IE, this handler may return an alternate keycode that is used in place of the key actually pressed by the user.

See Also

Event; Chapter 19

HTMLElement.onkeyupthe handler invoked when the user releases a key

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onkeyup=" handler" ... > 
element.onkeyup

Description

The onkeyup property of an HTMLElement object specifies an event handler function that is invoked when the user releases a key over the element.

The initial value of this property is a function that contains the JavaScript statements specified by the onkeyup attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onkeyup handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

Event, HTMLElement.onkeydown; Chapter 19

HTMLElement.onmousedownthe handler invoked when the user presses a mouse button

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onmousedown="handler" ... > 
element.onmousedown

Description

The onmousedown property of an HTMLElement object specifies an event handler function that is invoked when the user presses a mouse button over element.

The initial value of this property is a function that contains the JavaScript statements specified by the onmousedown attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onmousedown handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

In Netscape, the Event.which property specifies which mouse button was pressed. In IE, the Event.button property specifies the button number.

See Also

Event, HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

HTMLElement.onmousemovethe handler invoked when the mouse moves within an element

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onmousemove="handler" ... > 
element.onmousemove

Description

The onmousemove property of an HTMLElement object specifies an event handler function that is invoked when the user moves the mouse pointer within the element.

The initial value of this property is a function that contains the JavaScript statements specified by the onmousemove attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onmousemove handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

If you define an onmousemove event handler, mouse motion events are generated and reported in huge quantities when the mouse is moved within element. Keep this in mind when writing the function to be invoked by the event handler.

In Netscape 4, you cannot define this event handler on individual elements; instead, you must explicitly register your interest in mouse motion events by capturing them with the captureEvents( ) method of a Window, Document, or Layer object.

See Also

Event, Window.captureEvents( ); Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

HTMLElement.onmouseoutthe handler invoked when mouse moves out of an element

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onmouseout="handler" ... > 
element.onmouseout

Description

The onmouseout property of an HTMLElement object specifies an event handler function that is invoked when the user moves the mouse pointer out of the element.

The initial value of this property is a function that contains the JavaScript statements specified by the onmouseout attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onmouseout handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

Event, Link.onmouseout; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

HTMLElement.onmouseoverthe handler invoked when the mouse moves over an element

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onmouseover="handler" ... > 
element.onmouseover

Description

The onmouseover property of an HTMLElement object specifies an event handler function that is invoked when the user moves the mouse pointer over the element.

The initial value of this property is a function that contains the JavaScript statements specified by the onmouseover attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In Netscape 4, the onmouseover handler function is passed an Event object as an argument. In IE 4, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

Event, Link.onmouseover; Chapter 19

HTMLElement.onmouseupthe handler invoked when the user releases a mouse button

Availability

JavaScript 1.2; HTML 4.0

Synopsis

<element onmouseup="handler" ... > 
element.onmouseup

Description

The onmouseup property of an HTMLElement object specifies an event handler function that is invoked when the user releases a mouse button over the element.

The initial value of this property is a function that contains the JavaScript statements specified by the onmouseup attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onmouseup handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

In Netscape 4, the Event.which property specifies which mouse button was pressed. In IE, the Event.button property specifies the button number.

See Also

Event, HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

HTMLElement.removeAttribute( )delete an attribute

Availability

Internet Explorer 4, Netscape 6

Synopsis

element.removeAttribute(name)

Arguments

name
The name of the attribute to be deleted.

Returns

true on success; false on failure.

Description

removeAttribute( ) deletes the attribute name from element. If element does not have an attribute named name, this method returns false.

HTMLElement.scrollIntoView( )make an element visible

Availability

Internet Explorer 4

Synopsis

element.scrollIntoView(top)

Arguments

top
An optional boolean argument that specifies whether the element should be scrolled to the top or bottom of the screen. If true or omitted, element appears at the top of the screen. If false, element appears at the bottom of the screen.

Description

scrollIntoView( ) scrolls the document containing element so the top of element is aligned with the top of the display area or the bottom of element is aligned with the bottom of the display area.

HTMLElement.setAttribute( )set the value of an attribute

Availability

Internet Explorer 4, Netscape 6

Synopsis

element.setAttribute(name, value)

Arguments

name
The name of the attribute to set.

value
The value to set it to.

Description

setAttribute( ) sets the attribute name of element to value.

Imagean image in an HTML document

Availability

JavaScript 1.1

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

document.images[i] 
document.images.length
document.image-name

Constructor

new Image(width, height)

Arguments

width, height
An optionally specified width and height for the image.

Properties

Image inherits properties from HTMLElement and defines the following properties, most of which correspond to the HTML attributes of the <img> tag. In JavaScript 1.1 and later, the src and lowsrc properties are read/write and may be set to change the displayed image. In browsers that do not allow document reflow, such as IE 3 and Netscape 4, the other properties are read-only.

border
An integer that specifies the width, in pixels, of the border around an image. Its value is set by the border attribute. Images have borders only when they are within hyperlinks.

complete
A read-only boolean value that specifies whether an image is completely loaded or, more accurately, whether the browser has completed its attempt to load the image. If an error occurs during loading, or if the load is aborted, the complete property is still set to true.

height
An integer that specifies the height, in pixels, of the image. Its value is set by the height attribute.

hspace
An integer that specifies the amount of extra horizontal space, in pixels, inserted on the left and right of the image. Its value is set by the hspace attribute.

lowsrc
A read/write string that specifies the URL of an alternate image (usually a smaller one) to display when the user's browser is running on a low-resolution monitor. The initial value is specified by the lowsrc attribute of the <img> tag.

Setting this property has no immediate effect. If the src property is set, however, a new image is loaded, and on low-resolution systems, the current value of the lowsrc property is used instead of the newly updated value of src.

name
A string value, specified by the HTML name attribute, that specifies the name of the image. When an image is given a name with the name attribute, a reference to the image is placed in the image-name property of the document in addition to being placed in the document.images[] array.

src
A read/write string that specifies the URL of the image to be displayed by the browser. The initial value of this property is specified by the src attribute of the <img> tag. When you set this property to the URL of a new image, the browser loads and displays that new image (or, on low-resolution systems, the image specified by the lowsrc property). This is useful for updating the graphical appearance of your web pages in response to user actions and can also be used to perform simple animation.

vspace
An integer that specifies the amount of extra vertical space, in pixels, inserted above and below the image. Its value is set by the vspace attribute.

width
An integer that specifies the width, in pixels, of the image. Its value is set by the width attribute.

Event Handlers

Image inherits event handlers from HTMLElement and defines the following:

onabort
Invoked if the user aborts the download of an image.

onerror
Invoked if an error occurs while downloading the image.

onload
Invoked when the image successfully finishes loading.

HTML Syntax

The Image object is created with a standard HTML <img> tag. Some <img> attributes have been omitted from the following syntax because they are not used by or accessible from JavaScript:

<img src="url"              // The image to display
     width="pixels"         // The width of the image
     height="pixels"        // The height of the image
     [ name="image_name" ]  // A property name for the image
     [ lowsrc="url" ]       // Alternate low-resolution image
     [ border="pixels" ]    // Width of image border
     [ hspace="pixels" ]    // Extra horizontal space around image
     [ vspace="pixels" ]    // Extra vertical space around image
     [ onload="handler" ]   // Invoked when image is fully loaded
     [ onerror="handler" ]  // Invoked if error in loading
     [ onabort="handler" ]  // Invoked if user aborts load
>

Description

The Image objects in the document.images[] array represent the images embedded in an HTML document using the <img> tag. The src property is the most interesting one; when you set this property, the browser loads and displays the image specified by the new value.

You can create Image objects dynamically in your JavaScript code using the Image( ) constructor function. Note that this constructor method does not have an argument to specify the image to be loaded. As with images created from HTML, you tell the browser to load an image by setting the src property of any images you create explicitly. There is no way to display an Image object in the web browser. All you can do is force the Image object to download an image by setting the src property. This is useful, however, because it loads an image into the browser's cache. Later, if that same image URL is specified for one of the images in the images[] array, it is preloaded and displays quickly. You can do this with the following lines:

document.images[2].src = preloaded_image.src;
document.toggle_image.src = toggle_off.src; 

Usage

Setting the src property of an Image object is a way to implement simple animations in your web pages. It is also an excellent technique for changing the graphics on a page as the user interacts with the page. For example, you can create your own Submit button using an image and a hypertext link. The button will start out with a disabled graphic and remain that way until the user correctly enters all the required information into the form, at which point the graphic changes, and the user is able to submit the form.

Image.onabortthe handler invoked when the user aborts image loading

Availability

JavaScript 1.1

Synopsis

<img ... onabort="handler" ... >
image.onabort

Description

The onabort property of an Image object specifies an event handler function that is invoked when the user aborts the loading of an image (for example, by clicking the Stop button).

The initial value of this property is a function that contains the JavaScript statements specified by the onabort attribute of the <img> tag that defined the Image object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onabort handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

Image.onerrorthe handler invoked when an error occurs during image loading

Availability

JavaScript 1.1

Synopsis

<img ... onerror="handler" ... >
image.onerror

Description

The onerror property of an Image object specifies an event handler function that is invoked when an error occurs during the loading of an image.

The initial value of this property is a function that contains the JavaScript statements specified by the onerror attribute of the <img> tag that defined the Image object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onerror handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

Image.onloadthe handler invoked when an image finishes loading

Availability

JavaScript 1.1

Synopsis

<img ... onload="handler" ... >
image.onload

Description

The onload property of an Image object specifies an event handler function that is invoked when an image loads successfully.

The initial value of this property is a function that contains the JavaScript statements specified by the onload attribute of the <img> tag that defined the Image object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onload handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Inputan input element in an HTML form

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

form.elements[i] 
form.name

Properties

Input inherits properties from HTMLElement and defines or overrides the following:

checked
A read/write boolean that specifies whether a Checkbox or Radio form element is currently checked. You can set the state of these button elements by setting the value of this property. This property is not used by other form elements.

defaultChecked
A read-only boolean value that specifies whether a Checkbox or Radio element is checked by default. This property is used to restore the Checkbox or Radio element to its default value when the form is reset and has no meaning for other form elements. defaultChecked corresponds to the checked attribute in the HTML <input> tag that created the form element. If checked was present, defaultChecked is true. Otherwise, defaultChecked is false.

defaultValue
Specifies the initial text that appears in the form element and the value that is restored to that element when the form is reset. This property is used only by the Text, Textarea, and Password elements. For security reasons, it is not used by the FileUpload element. For Checkbox and Radio elements, the equivalent property is defaultChecked.

form
A read-only reference to the Form object that contains the element. The form property allows the event handlers of one form element to easily refer to sibling elements in the same form. When an event handler is invoked, the this keyword refers to the form element for which it was invoked. Thus, an event handler can use the expression this.form to refer to the form that contains it. From there, it can refer to sibling elements by name or use the elements[] array of the Form object to refer to them by number.

length
For the Select form element, this property specifies the number of options or choices (each represented by an Option object) that are contained within the options[] array of the element. See the Select reference page.

name
A read-only string, specified by the HTML name attribute, that specifies the name of this element. This name may be used to refer to the element, as shown in the preceding Section section. See the Input.name reference page.

options[]
For the Select form element, this array contains Option objects that represent the options or choices displayed by the Select object. The number of elements in the array is specified by the length property of the Select element. See the Input.name reference page.

selectedIndex
For the Select form element, this integer specifies which option displayed by the Select object is currently selected. In JavaScript 1.1, this property is read/write. In JavaScript 1.0, it is read-only. See the Input.name reference page.

type [ JavaScript 1.1]
A read-only string that specifies the type of the form element. See the Input.type reference page.

value
A string that specifies the value displayed by the element and/or to be sent to the server for this element when the form that contains it is submitted. See the Input.value reference page.

Methods

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

blur( )
Removes keyboard focus from the element.

click( )
Simulates a mouse-click on the form element.

focus( )
Gives keyboard focus to the element.

select( )
For form elements that display editable text, selects the text that appears in the element.

Event Handlers

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

onblur
Invoked when the user takes keyboard focus away from the element.

onchange
For form elements that are not buttons, this event handler is invoked when the user enters or selects a new value.

onclick
For form elements that are buttons, this event handler is invoked when the user clicks or selects the button.

onfocus
Invoked when the user gives keyboard focus to the element.

Description

Form elements are stored in the elements[] array of the Form object. The contents of this array are Input objects, which represent the individual buttons, input fields, and other controls that appear within the form. Many types of input elements are created with the <input> tag; others are created with the <select> and <option> tags and the <textarea> tag. The various form input elements share quite a few properties, methods, and event handlers, which are described on this reference page. Specific behaviors for specific types of form elements are described on their own pages.

The Input object defines many shared properties, methods, and event handlers, but not all of them are shared by all types of form elements. For example, the Button object triggers the onclick event handler but not the onchange handler, while the Text object triggers onchange but not onclick. The following figure shows all of the form elements and the properties associated with them.

Figure

There are two broad categories of form elements. The first is the buttons: Button, Checkbox, Radio, Reset, and Submit. These elements have an onclick event handler but not an onchange handler. Similarly, they respond to the click( ) method but not to the select( ) method. The second category contains those elements that display text: Text, Textarea, Password, and FileUpload. These elements have an onchange event handler rather than an onclick handler, and they respond to the select( ) method but not to the click( ) method.

The Select element is a special case. It is created with the <select> tag and is less like the <input> elements than the other form elements. Although the Select element is technically represented by a different object type, it is still convenient to consider it an Input object.

See Also

Button, Checkbox, FileUpload, Form, Hidden, Password, Radio, Reset, Select, Submit, Text, Textarea; Chapter 15; HTMLInputElement in the DOM reference section

Input.blur( )remove keyboard focus from a form element

Availability

JavaScript 1.0

Synopsis

input.blur( ) 

Description

The blur( ) method of a form element removes keyboard focus from that element without invoking the onblur event handler; it is essentially the opposite of the focus( ) method. The blur( ) method does not transfer keyboard focus anywhere, however, so the only time that it is actually useful to call this method right before you transfer keyboard focus elsewhere with the focus( ) method, when you don't want to trigger the onblur event handler. That is, by removing focus explicitly from the element, you won't be notified when it is removed implicitly by a focus( ) call on another element.

All form elements other than Hidden support the blur( ) method. Unfortunately, not all platforms support keyboard navigation equally well. In Netscape 2 and 3 for Unix platforms, the blur( ) method is functional only for those form elements that display text: Text, Textarea, Password, and FileUpload.

Input.click( )simulate a mouse-click on a form element

Availability

JavaScript 1.0

Synopsis

input.click( ) 

Description

The click( ) method of a form element simulates a mouse-click on the form element but does not invoke the onclick event handler of the element.

The click( ) method is not often useful. Because it does not invoke the onclick event handler, it is not useful to call this method on Button elements -- they don't have any behavior other than that defined by the onclick handler. Calling click( ) on a Submit or Reset element submits or resets a form, but this can be more directly achieved with the submit( ) and reset( ) method of the Form object itself.

Input.focus( )give keyboard focus to a form element

Availability

JavaScript 1.0

Synopsis

input.focus( ) 

Description

The focus( ) method of a form element transfers keyboard focus to that element without calling the onfocus event handler. That is, it makes the element active with respect to keyboard navigation and keyboard input. Thus, if you call focus( ) for a Text element, any text the user types appears in that text element. Or, if you call focus( ) for a Button element, the user can invoke that button from the keyboard.

All form elements except the Hidden element support the focus( ) method. Unfortunately, not all platforms support keyboard navigation equally well. In Unix versions of Netscape, focus( ) is functional only for those form elements that display text: Text, Textarea, Password, and FileUpload.

Input.namethe name of a form element

Availability

JavaScript 1.0

Synopsis

input.name 

Description

name is a read-only string property of every form element. The value of this property is set by the name attributes of the HTML <input> tag that defines the form element.

The name of a form element is used for two purposes. First, it is used when the form is submitted. Data for each element in the form is usually submitted in the format:

name=value

where name and value are encoded as necessary for transmission. If a name is not specified for a form element, the data for that element cannot be submitted to a web server.

The second use of the name property is to refer to a form element in JavaScript code. The name of an element becomes a property of the form that contains the element. The value of this property is a reference to the element. For example, if address is a form that contains a text input element with the name zip, address.zip refers to that text input element.

With Radio and Checkbox form elements, it is common to define more than one related object, each of which have the same name property. In this case, data is submitted to the server with this format:

name=value1,value2,...,valuen

Similarly, in JavaScript, each of the elements that shares a name becomes an element of an array with that name. Thus, if four Checkbox objects in the form order share the name options, they are available in JavaScript as elements of the array order.options[].

Input.onblurthe handler invoked when a form element loses focus

Availability

JavaScript 1.0

Synopsis

<input type="type"onblur="handler"> 
input.onblur

Description

The onblur property of an Input object specifies an event handler function that is invoked when the user transfers keyboard focus away from that input element. Calling blur( ) to remove focus from an element does not invoke onblur for that object. Note, however, that calling focus( ) to transfer focus to some other element causes the onblur event handler to be invoked for whichever element currently has the focus.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onblur attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onblur handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

The onblur event handler is available for all form elements except the Hidden element. In Netscape on Unix platforms, however, it is invoked only for the text-entry elements: Text, Textarea, Password, and FileUpload. Note that in JavaScript 1.1, the Window object also defines an onblur event handler.

See Also

Window.onblur; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Input.onchangethe handler invoked when a form element's value changes

Availability

JavaScript 1.0

Synopsis

<input type="type"onchange="handler"> 
input.onchange

Description

The onchange property of an Input object specifies an event handler function that is invoked when the user changes the value displayed by a form element. Such a change may be an edit to the text displayed in Text, Textarea, Password, or FileUpload elements, or the selection or deselection of an option in a Select element. Note that this event handler is only invoked when the user makes such a change -- it is not invoked if a JavaScript program changes the value displayed by an element.

Also note that the onchange handler is not invoked every time the user enters or deletes a character in a text-entry form element. onchange is not intended for that type of character-by-character event handling. Instead, onchange is invoked when the user's edit is complete. The browser assumes that the edit is complete when keyboard focus is moved from the current element to some other element -- for example, when the user clicks on the next element in the form. See the HTMLElement.onkeypress reference page for character-by-character event notification.

The onchange event handler is not used by the Hidden element or by any of the button elements. Those elements -- Button, Checkbox, Radio, Reset, and Submit -- use the onclick event handler instead.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onchange attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onchange handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

HTMLElement.onkeypress; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Input.onclickthe handler invoked when a form element is clicked

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

<input type="type"onclick="handler"> 
input.onclick

Description

The onclick property of an Input object specifies an event handler function that is invoked when the user clicks on the input element. It is not invoked when the click( ) method is called for the element.

Only form elements that are buttons invoke the onclick event handler. These are the Button, Checkbox, Radio, Reset, and Submit elements. Other form elements use the onchange event handler instead of onclick.

The initial value of the onclick property is a function containing the semicolon-separated JavaScript statements specified by the onclick attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onclick handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

Note that the Reset and Submit elements perform a default action when clicked: they reset and submit, respectively, the form that contains them. You can use the onclick event handlers of each of these elements to perform actions in addition to these default actions. In JavaScript 1.1, you can also prevent these default actions by returning false. That is, if the onclick handler of a Reset button returns false, the form is not reset, and if the onclick handler of a Submit button returns false, the form is not submitted. Note that you do similar things with the onsubmit and onreset event handlers of the Form object itself.

Finally, note that the Link object also defines an onclick event handler.

See Also

Link.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Input.onfocusthe handler invoked when a form element gains focus

Availability

JavaScript 1.0

Synopsis

<input type="type"onfocus="handler"> 
input.onfocus

Description

The onfocus property of an Input object specifies an event handler function that is invoked when the user transfers keyboard focus to that input element. Calling focus( ) to set focus to an element does not invoke onfocus for that object.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onfocus attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onfocus handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

The onfocus event handler is available for all form elements except the Hidden element. In Netscape on Unix platforms, however, it is invoked only for the text-entry elements: Text, Textarea, Password, and FileUpload. Note that in JavaScript 1.1, the Window object also defines an onfocus event handler.

See Also

Window.onfocus; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Input.select( )select the text in a form element

Availability

JavaScript 1.0

Synopsis

input.select( ) 

Description

The select( ) method selects the text displayed in a Text, Textarea, Password, or FileUpload element. The effects of selecting text may vary from platform to platform, but typically, invoking this method produces the same result as the user dragging the mouse across all the text in the specified Text object. On most platforms, this produces the following effects:

The user can usually deselect text by clicking in the Text object or by moving the cursor. Once deselected, the user can add and delete individual characters without replacing the entire text value.

Input.typethe type of a form element

Availability

JavaScript 1.1

Synopsis

input.type 

Description

type is a read-only string property of all form elements that specifies the type of the form element. The value of this property for each possible form element is given in the following table.

Object type

HTML tag

type property

Button

<input type="button">

"button"

Checkbox

<input type="checkbox">

"checkbox"

FileUpload

<input type="file">

"file"

Hidden

<input type="hidden">

"hidden"

Password

<input type="password">

"password"

Radio

<input type="radio">

"radio"

Reset

<input type="reset">

"reset"

Select

<select>

"select-one"

Select

<select multiple>

"select-multiple"

Submit

<input type="submit">

"submit"

Text

<input type="text">

"text"

Textarea

<textarea>

"textarea"

Note that the Select element has two possible type values, depending on whether it allows single or multiple selection. Also note that unlike other input element properties, type is not available in JavaScript 1.0.

Input.valuethe value displayed or submitted by a form element

Availability

Netscape 2; buggy in Internet Explorer 3

Synopsis

input.value 

Description

value is a read/write string property of all form elements that specifies the value displayed by the form element and/or submitted for the element when the form is submitted. The value property of the Text element, for example, is the user's input, which is also the value submitted with the form. For the Checkbox object, on the other hand, the value property specifies a string that is not displayed but is submitted with the form if the Checkbox element is checked when the form is submitted.

The initial value of the value property is specified by the value attribute of the HTML tag that defines the form element.

For Button, Submit, and Reset objects, the value property specifies the text that appears within the button. On some platforms, changing the value property of these elements actually changes the text displayed by the buttons onscreen. This does not work on all platforms, however, and is not an advisable technique. Changing the label of a button may change the size of the button, causing it to overlap and obscure other portions of the document.

The Select element has a value property, like all form elements, but does not use it. Instead, the value submitted by this element is specified by the value property of the Option objects it contains.

For security reasons, the value property of the FileUpload element is read-only.

JavaArrayJavaScript representation of a Java array

Availability

Netscape 3 LiveConnect

Synopsis

javaarray.length // The length of the array 
javaarray[index] // Read or write an array element

Properties

length
A read-only integer that specifies the number of elements in the Java array represented by the JavaArray object.

Description

The JavaArray object is a JavaScript representation of a Java array that allows JavaScript code to read and write the elements of the array using familiar JavaScript array syntax. In addition, the JavaArray object has a length field that specifies the number of elements in the Java array.

When reading and writing values from array elements, data conversion between JavaScript and Java representations is automatically handled by the system. See Chapter 22 for full details.

Usage

Note that Java arrays differ from JavaScript arrays in a couple of important aspects. First, Java arrays have a fixed length that is specified when they are created. For this reason, the JavaArray length field is read-only. The second difference is that Java arrays are typed (i.e., their elements must all be of the same type of data). Attempting to set an array element to a value of the wrong type results in a JavaScript error or exception.

Example

java.awt.Polygon is a JavaClass object. We can create a JavaObject representing an instance of the class like this:

p = new java.awt.Polygon( ); 

The object p has properties xpoints and ypoints, which are JavaArray objects representing Java arrays of integers. We can initialize the contents of these arrays with JavaScript code like the following:

for(int i = 0; i < p.xpoints.length; i++)
    p.xpoints[i] = Math.round(Math.random( )*100);
for(int i = 0; i < p.ypoints.length; i++)
    p.ypoints[i] = Math.round(Math.random( )*100); 

See Also

getClass( ), JavaClass, JavaObject, JavaPackage, the java property of the Window object; Chapter 22

JavaClassJavaScript representation of a Java class

Availability

Netscape 3 LiveConnect

Synopsis

javaclass.static_member // Read or write a static Java field or method 
new javaclass(...) // Create a new Java object

Properties

Each JavaClass object contains properties that have the same names as the public static fields and methods of the Java class it represents. These properties allow you to read and write the static fields of the class and invoke the static methods of the class. Each JavaClass object has different properties; you can use a for/in loop to enumerate them for any given JavaClass object.

Description

The JavaClass object is a JavaScript representation of a Java class. The properties of a JavaClass object represent the public static fields and methods (sometimes called class fields and class methods) of the represented class. Note that the JavaClass object does not have properties representing the instance fields of a Java class -- individual instances of a Java class are represented by the JavaObject object.

The JavaClass object implements the LiveConnect functionality that allows JavaScript programs to read and write the static variables of Java classes using normal JavaScript syntax. It also provides the functionality that allows JavaScript to invoke the static methods of a Java class.

In addition to allowing JavaScript to read and write Java variable and method values, the JavaClass object allows JavaScript programs to create Java objects (represented by a JavaObject object) by using the new keyword and invoking the constructor method of a JavaClass.

The data conversion required for communication between JavaScript and Java through the JavaClass object is handled automatically by LiveConnect. See Chapter 22 for full details.

Usage

Bear in mind that Java is a typed language. This means that each of the fields of an object has a specific data type that is set to values of only that type. Attempting to set a field to a value that is not of the correct type results in a JavaScript error or exception. Attempting to invoke a method with arguments of the wrong type also causes an error or exception.

Example

java.lang.System is a JavaClass object that represents the java.lang.System class in Java. You can read a static field of this class with code like the following:

var java_console = java.lang.System.out; 

You can invoke a static method of this class with a line like this one:

var version = java.lang.System.getProperty("java.version"); 

Finally, the JavaClass object also allows you to create new Java objects:

var java_date = new java.lang.Date( ); 

See Also

getClass( ), JavaArray, JavaObject, JavaPackage, the java property of the Window object; Chapter 22

JavaObjectJavaScript representation of a Java object

Availability

Netscape 3 LiveConnect

Synopsis

javaobject.member // Read or write an instance field or method

Properties

Each JavaObject object contains properties that have the same names as the public instance fields and methods (but not the static or class fields and methods) of the Java object it represents. These properties allow you to read and write the value of public fields and invoke the public methods. The properties of a given JavaObject object obviously depend on the type of Java object it represents. You can use the for/in loop to enumerate the properties of any given JavaObject.

Description

The JavaObject object is a JavaScript representation of a Java object. The properties of a JavaObject object represent the public instance fields and public instance methods defined for the Java object. (The class or static fields and methods of the object are represented by the JavaClass object.)

The JavaObject object implements the LiveConnect functionality that allows JavaScript programs to read and write the public instance fields of a Java object using normal JavaScript syntax. It also provides the functionality that allows JavaScript to invoke the methods of a Java object. Data conversion between JavaScript and Java representations is handled automatically by LiveConnect. See Chapter 22 for full details.

Usage

Bear in mind that Java is a typed language. This means that each of the fields of an object has a specific data type, and you can set it only to values of that type. For example, the width field of a java.awt.Rectangle object is an integer field, and attempting to set it to a string causes a JavaScript error or exception.

Example

java.awt.Rectangle is a JavaClass that represents the java.awt.Rectangle class. We can create a JavaObject that represents an instance of this class like this:

var r = new java.awt.Rectangle(0,0,4,5); 

We can then read the public instance variables of this JavaObject r with code like this:

var perimeter = 2*r.width + 2*r.height; 

We can also set the value of public instance variables of r using JavaScript syntax:

r.width = perimeter/4;
r.height = perimeter/4; 

See Also

getClass( ), JavaArray, JavaClass, JavaPackage, the java property of the Window object; Chapter 22

JavaPackageJavaScript representation of a Java package

Availability

Netscape 3 LiveConnect

Synopsis

package.package_name // Refers to another JavaPackage
package.class_name // Refers to a JavaClass object

Properties

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

Description

The JavaPackage object is a JavaScript representation of a Java package. A package in Java is a collection of related classes. In JavaScript, a JavaPackage can contain classes (represented by the JavaClass object) and other JavaPackage objects.

The Window object has properties java, netscape, and sun that represent the java.*, netscape.*, and sun.* package hierarchies. These JavaPackage objects define properties that refer to other JavaPackage objects. For example, java.lang and java.net refer to the java.lang and java.net packages. The java.awt JavaPackage contains properties named Frame and Button, which are both references to JavaClass objects and represent the classes java.awt.Frame and java.awt.Button.

The Window object also defines a property named Packages, which is the root JavaPackage whose properties refer to the roots of all known package hierarchies. For example, the expression Packages.java.awt is the same as java.awt.

It is not possible to use the for/in loop to determine the names of the packages and classes contained within a JavaPackage. You must have this information in advance. You can find it in any Java reference manual or by examining the Java class hierarchy.

See Chapter 22 for further details on working with Java packages, classes, and objects.

See Also

JavaArray, JavaClass, JavaObject; the java, netscape, sun, and Packages properties of the Window object; Chapter 22

JSObjectJava representation of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public final class netscape.javascript.JSObject extends Object 

Methods

call( )
Invokes a method of the JavaScript object.

eval( )
Evaluates a string of JavaScript code in the context of the JavaScript object.

getMember( )
Gets the value of a property of the JavaScript object.

getSlot( )
Gets the value of an array element of the JavaScript object.

getWindow( )
Gets a "root" JSObject that represents the JavaScript Window object of the web browser.

removeMember( )
Deletes a property from the JavaScript object.

setMember( )
Sets the value of a property of the JavaScript object.

setSlot( )
Sets the value of an array element of the JavaScript object.

toString( )
Invokes the JavaScript toString( ) method of the JavaScript object and returns its result.

Description

The JSObject is a Java class, not a JavaScript object; it cannot be used in your JavaScript programs. Instead, the JSObject is used by Java applets that wish to communicate with JavaScript by reading and writing JavaScript properties and array elements, invoking JavaScript methods, and evaluating and executing arbitrary strings of JavaScript code. Obviously, since JSObject is a Java class, you must understand Java programming in order to use it.

Full details on programming with the JSObject can be found in Chapter 22.

See Also

Chapter 22

JSObject.call( )invoke a method of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public Object call(String methodName, Object args[])

Arguments

methodName
The name of the JavaScript method to be invoked.

args[]
An array of Java objects to be passed as arguments to the method.

Returns

A Java object that represents the return value of the JavaScript method.

Description

The call( ) method of the Java JSObject class invokes a named method of the JavaScript object represented by the JSObject. Arguments are passed to the method as an array of Java objects, and the return value of the JavaScript method is returned as a Java object.

Chapter 22 describes the data conversion of the method arguments from Java objects to JavaScript values and the method return value from a JavaScript value to a Java object.

JSObject.eval( )evaluate a string of JavaScript code

Availability

Netscape 3, Internet Explorer 4

Synopsis

public Object eval(String s) 

Arguments

s
A string that contains arbitrary JavaScript statements separated by semicolons.

Returns

The JavaScript value of the last expression evaluated in s, converted to a Java object.

Description

The eval( ) method of the Java JSObject class evaluates the JavaScript code contained in the string s in the context of the JavaScript object specified by the JSObject. The behavior of the eval( ) method of the Java JSObject class is much like that of the JavaScript global eval( ) function.

The argument s may contain any number of JavaScript statements separated by semicolons; these statements are executed in the order in which they appear. The return value of eval( ) is the value of the last statement or expression evaluated in s.

JSObject.getMember( )read a property of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public Object getMember(String name) 

Arguments

name
The name of the property to be read.

Returns

A Java object that contains the value of the named property of the specified JSObject.

Description

The getMember( ) method of the Java JSObject class reads and returns to Java the value of a named property of a JavaScript object. The return value may be another JSObject object or a Double, Boolean, or String object, but it is returned as a generic Object, which you must cast as necessary.

JSObject.getSlot( )read an array element of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public Object getSlot(int index) 

Arguments

index
The index of the array element to be read.

Returns

The value of the array element at the specified index of a JavaScript object.

Description

The getSlot( ) method of the Java JSObject class reads and returns to Java the value of an array element at the specified index of a JavaScript object. The return value may be another JSObject object or a Double, Boolean, or String object, but it is returned as a generic Object, which you must cast as necessary.

JSObject.getWindow( )return initial JSObject for browser window

Availability

Netscape 3, Internet Explorer 4

Synopsis

public static JSObject getWindow(java.applet.Applet applet)

Arguments

applet
An Applet object running in the web browser window for which a JSObject is to be obtained.

Returns

A JSObject that represents the JavaScript Window object for the web browser window that contains the specified applet.

Description

The getWindow( ) method is the first JSObject method that any Java applet calls. JSObject does not define a constructor, and the static getWindow( ) method provides the only way to obtain an initial "root" JSObject from which other JSObjects may be obtained.

JSObject.removeMember( )delete a property of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public void removeMember(String name) 

Arguments

name
The name of the property to be deleted from the JSObject.

Description

The removeMember( ) method of the Java JSObject class deletes a named property from the JavaScript object represented by the JSObject.

JSObject.setMember( )set a property of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public void setMember(String name, Object value)

Arguments

name
The name of the property to be set in the JSObject.

value
The value to which the named property should be set.

Description

The setMember( ) method of the Java JSObject class sets the value of a named property of a JavaScript object from Java. The specified value may be any Java Object. Primitive Java values may not be passed to this method. In JavaScript, the specified value is accessible as a JavaObject object.

JSObject.setSlot( )set an array element of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public void setSlot(int index, Object value)

Arguments

index
The index of the array element to be set in the JSObject.

value
The value to which the specified array element should be set.

Description

The setSlot( ) method of the Java JSObject class sets the value of a numbered array element of a JavaScript object from Java. The specified value may be any Java Object. Primitive Java values may not be passed to this method. In JavaScript, the specified value is accessible as a JavaObject object.

JSObject.toString( )return the string value of a JavaScript object

Availability

Netscape 3, Internet Explorer 4

Synopsis

public String toString( ) 

Returns

The string returned by invoking the toString( ) method of the JavaScript object represented by the specified Java JSObject.

Description

The toString( ) method of the Java JSObject class invokes the JavaScript toString( ) method of the JavaScript object represented by a JSObject and returns the result of that method.

Layeran independent layer in a DHTML document

Availability

Netscape 4 only; discontinued in Netscape 6

Synopsis

document.layers[i] 

Constructor

new Layer(width, parent)

Arguments

width
The width of the new layer, in pixels.

parent
The Layer or Window that should be the parent of this newly created layer. This argument is optional; if omitted, the new layer is a child of the current window.

Notes

The Layer( ) constructor creates a new Layer object and returns it. You can set its size, position, and other attributes with the various Layer properties and methods described in the following lists. In particular, you must set the hidden property to false to make the new layer visible. See the src property and load( ) methods in particular for ways to set the content of a layer. Alternatively, you can dynamically generate content for the layer by writing to its document property.

Note that you can only call the Layer( ) constructor once the current document and all of its layers have finished loading.

Properties

above
A read-only property that refers to the Layer object immediately above layer in the stacking order. If there is no such layer, above is null.

background
An Image object that specifies the image displayed in the background of the layer. The initial value of this property is specified by the background attribute of the <layer> tag. You can change the image displayed in the background of the layer by setting the background.src property. If set to null, no image is displayed, and the background color (specified by bgColor) is displayed instead.

below
A read-only property that refers to the Layer object immediately below layer in the stacking order. If there is no such layer, below is null.

bgColor
A read/write string property that specifies the background color of layer. The initial value of this property is specified by the bgcolor attribute of the <layer> tag. Note that layer.background takes precedence over layer.bgColor, so the color specified by this property appears only if the background.src property of layer is null.

clip.bottom
The Y-coordinate of the bottom edge of the layer's clipping area, relative to layer.top.

clip.height
The height of the layer's clipping area. Setting this property also sets the value of layer.clip.bottom.

clip.left
Specifies the X-coordinate of the left edge of the layer's clipping area. This value is relative to layer.left.

clip.right
Specifies the X-coordinate of the right edge of the layer's clipping area. This value is relative to layer.left.

clip.top
Specifies the Y-coordinate of the top edge of the layer's clipping area. This value is relative to layer.top.

clip.width
Specifies the width of the layer's clipping area. Setting this property also sets the value of layer.clip.right.

document
A read-only reference to the Document object contained within that layer.

hidden
Specifies whether a layer is hidden (true) or visible (false). Setting this property to true hides the layer, and setting it to false makes the layer visible.

layers[]
An array that contains any child Layer objects of this layer. It is the same as the document.layers[] array of a layer.

left
A read/write integer that specifies the X-coordinate, relative to the containing layer or document, of this layer. Setting this property moves the layer to the left or right. left is a synonym for x.

name
A read/write string that specifies the name of a layer. The initial value of this property is specified by the name or id attributes of the HTML tag used to create the layer and is also used as the name of the Document property that refers to the Layer object.

pageX, pageY
Read/write integers that specify the X- and Y-coordinates of this layer relative to the top-level document. Note that these coordinates are relative to the top-level page, not relative to any containing layer.

parentLayer
A read-only reference to the Layer or Window object that contains (is the parent of ) this layer.

siblingAbove, siblingBelow
Refer to the sibling Layer object (i.e., a child of the same parent Layer) immediately above or below this layer in the stacking order. If there is no such layer, these properties are null.

src
A read/write string that specifies the URL, if any, of the contents of a layer. Setting this property to a new URL causes the browser to read the contents of that URL and display them in the layer. Note, however, that this does not work while the current document is being parsed. For this reason, you should not set src in a top-level script; instead, set it in an event handler or a function called from an event handler.

top
A read/write integer that specifies the Y-coordinate of this layer relative to the containing layer or document. Setting this property moves the layer up or down. top is a synonym for y.

visibility
A read/write string that specifies the visibility of the layer. There are three possible legal values: "show" specifies that the layer should be visible; "hide" specifies that the layer should not be visible; "inherit" specifies that the layer should inherit the visibility of its parent layer.

window
Refers to the Window object that contains the layer, regardless of how deeply nested the layer is within other layers.

x, y
The X- and Y-coordinates of the layer, relative to the containing layer or document. Setting these properties move the layer. x is a synonym for the left property, and y is a synonym for the top property.

zIndex
Specifies the position of the layer in the z-order, or stacking order, of layers. When two layers overlap, the one with the higher zIndex appears on top and obscures the one with the lower zIndex. If two sibling layers have the same zIndex, the one that appears later in the layers[] array of the containing document is displayed later and overlaps any that appear earlier.

zIndex is a read/write property. Setting this property changes the stacking order and redisplays the layers in the new order. Setting this property may reorder the layers[] array of the containing document.

Methods

captureEvents( )
Specifies event types to be captured.

handleEvent( )
Dispatches an event to the appropriate handler.

load( )
Loads a new URL and resize.

moveAbove( )
Moves this layer above another.

moveBelow( )
Moves this layer below another.

moveBy( )
Moves the layer to a relative position.

moveTo( )
Moves the layer to a position relative to its containing layer.

moveToAbsolute( )
Moves the layer to a position relative to the page.

offset( )
A synonym for moveBy( ).

releaseEvents( )
Stops capturing specified event types.

resizeBy( )
Resizes the layer by the specified amounts.

resizeTo( )
Resizes the layer to the specified size.

routeEvent( )
Routes an event to the next interested handler.

HTML Syntax

A Layer object can be created with the Netscape-specific <layer> tag in HTML:

<layer
   [ id="layername" ]         // Layer name
   [ left="x" ]               // Position relative to containing layer
   [ top="y" ]
   [ pagex="x" ]              // Position relative to top-level document
   [ pagey="y" ]
   [ width="w" ]              // Size of layer
   [ height="h" ]
   [ src="url" ]              // URL of layer contents
   [ clip="x,y,w,h" ]         // Clipping rectangle for layer
   [ clip="w,h" ]             // Alternate syntax: x,y default to 0
   [ zindex="z" ]             // Stacking order
   [ above="layername" ]      // Alternative ways of specifying stacking
   [ below="layername" ]
   [ visibility="vis" ]       // "show", "hide", or "inherit"
   [ bgcolor="color" ]        // Background color of layer
   [ background="url" ]       // Background image of layer
   [ onmouseover="handler" ]  // Invoked when mouse enters layer
   [ onmouseout="handler" ]   // Invoked when mouse leaves layer
   [ onfocus="handler" ]      // Invoked when layer gets focus
   [ onblur="handler" ]       // Invoked when layer loses focus
   [ onload="handler" ]       // Invoked when layer's contents are loaded
>

Description

The Layer object is Netscape 4's technique for supporting dynamically positionable HTML elements. Note, however, that the Layer object was never standardized and is no longer supported in Netscape 6. A Layer object can be created in three ways: with the <layer> tag; with the Layer( ) constructor; or, most portably, with CSS style attributes on HTML elements, as explained in Chapter 18.

See Also

Window; Chapter 18

Layer.captureEvents( )see Window.captureEvents( )

Layer.handleEvent( )see Window.handleEvent( )

Layer.load( )change layer contents and width

Availability

Netscape 4 only

Synopsis

layer.load(src, width)

Arguments

src
A string that specifies the URL of the document to be loaded into layer.

width
An integer that specifies a new width, in pixels, for layer.

Description

load( ) loads a new document into layer and specifies a width at which the lines of that document are wrapped.

Note, however, that load( ) does not work while the current document is being parsed. For this reason, you should not call load( ) in a top-level script; instead, call it in an event handler or a function called from an event handler.

See Also

The src property of the Layer object

Layer.moveAbove( )move one layer above another Netscape 4 only

Synopsis

layer.moveAbove(target) 

Arguments

target
The reference Layer object above which layer is to be placed.

Description

moveAbove( ) changes the stacking order so layer appears on top of target. layer becomes a sibling of target if it is not one already. layer is given the same zIndex as target and is placed after target in the layers[] array of the containing document.

Layer.moveBelow( )move one layer below another Netscape 4 only

Synopsis

layer.moveBelow(target)

Arguments

target
The reference Layer object below which layer is to be placed.

Description

moveBelow( ) changes the stacking order so layer appears beneath target. layer becomes a sibling of target if it is not one already. layer is given the same zIndex as target and is placed before target in the layers[] array of the containing document.

Layer.moveBy( )move a Layer to a relative position Netscape 4 only

Synopsis

layer.moveBy(dx, dy)

Arguments

dx
The number of pixels to move the layer to the right (may be negative).

dy
The number of pixels to move the layer down (may be negative).

Description

moveBy( ) moves layer dx pixels to the right and dy pixels down from its current position.

Layer.moveTo( )move a Layer Netscape 4 only

Synopsis

layer.moveTo(x, y)

Arguments

x
The desired X-coordinate of the layer.

y
The desired Y-coordinate of the layer.

Description

moveTo( ) moves the upper-left corner of layer to the coordinates specified by x and y. Note that these coordinates are expressed relative to the containing layer or document.

Layer.moveToAbsolute( )move a Layer to page coordinates

Availability

Netscape 4 only

Synopsis

layer.moveToAbsolute(x, y)

Arguments

x
The desired X-coordinate of the layer.

y
The desired Y-coordinate of the layer.

Description

moveToAbsolute( ) moves the upper-left corner of layer to the document coordinates specified by x and y. Note that these coordinates are expressed relative to the page or top-level document, not relative to any containing layers.

Layer.offset( )move a Layer to a relative position

Availability

Netscape 4 only; deprecated

Synopsis

layer.offset(dx, dy)

Arguments

dx
The number of pixels to move the layer to the right (may be negative).

dy
The number of pixels to move the layer down (may be negative).

Description

offset( ) moves a layer relative to its current position. offset( ) is deprecated in favor of moveBy( ).

Layer.releaseEvents( )see Window.releaseEvents( )

Layer.resizeBy( )resize a Layer by a relative amount

Availability

Netscape 4 only

Synopsis

layer.resizeBy(dw, dh)

Arguments

dw
The number of pixels by which to increase the width of the window (may be negative).

dh
The number of pixels by which to increase the height of the window (may be negative).

Description

resizeBy( ) resizes layer by incrementing its clip.width and clip.height properties by dw and dh. It does not cause the contents of the layer to be reformatted, so making a layer smaller may clip the layer's contents.

Layer.resizeTo( )resize a Layer Netscape 4 only

Synopsis

layer.resizeTo(width, height)

Arguments

width
The desired width of the layer.

height
The desired height of the layer.

Description

resizeTo( ) resizes layer by setting its clip.width and clip.height properties to width and height. It does not cause the contents of the layer to be reformatted, so making a layer smaller may clip the layer's contents.

Layer.routeEvent( )see Window.routeEvent( )

Linka hypertext link

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

document.links[] 
document.links.length

Properties

Link inherits properties from HTMLElement and defines the following properties. Many of the properties represent portions of a URL. For each of these properties, the example given is a portion of the following (fictitious) URL:

http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results 
hash
A read/write string property that specifies the anchor portion of the Link's URL, including the leading hash (#) mark. For example: "#result". This anchor portion of a URL refers to a named position within the document referenced by the Link. In HTML files, positions are named with anchors created with the <a name="anchor_name"> tag.

host
A read/write string property that specifies the hostname and port portions of a Link's URL. For example, "www.oreilly.com:1234".

hostname
A read/write string property that specifies the hostname portion of a Link's URL. For example "www.oreilly.com".

href
A read/write string property that specifies the complete text of the Link's URL, unlike other Link URL properties that specify only portions of the URL.

pathname
A read/write string property that specifies the pathname portion of a Link's URL. For example "/catalog/search.html".

port
A read/write string (not a number) property that specifies the port portion of a Link's URL. For example "1234".

protocol
A read/write string property that specifies the protocol portion of a Link's URL, including the trailing colon. For example, "http:".

search
A read/write string property that specifies the query portion of a Link's URL, including the leading question mark. For example, "?q=JavaScript&m=10".

target
A read/write string property that specifies the name of a Window object (i.e., a frame or a top-level browser window) in which the linked document should be displayed. See the Link.target reference page for details.

text [Netscape 4]
Specifies the plain text, if any, between the <a> and </a> tags of a link. Note that this property works correctly only if there are no intervening HTML tags between the <a> and </a> tags. If there are other HTML tags, the text property may contain only a portion of the link text. HTMLElement.innerText provides the IE 4 equivalent of this Netscape-specific property.

Methods

Link inherits the methods of HTMLElement.

Event Handlers

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

onclick
Invoked when the user clicks on the link. In JavaScript 1.1, this event handler may prevent the link from being followed by returning false. On Windows platforms in Netscape 3, this event handler does not work for links created with the <area> tag.

onmouseout
Invoked when the user moves the mouse off the link. Available in JavaScript 1.1 and later.

onmouseover
Invoked when the user moves the mouse over the link. The status property of the current window may be set here. May return true to tell the browser not to display the URL of the link.

HTML Syntax

A Link object is created with standard <a> and </a> tags. The href attribute is required for all Link objects. If the name attribute is also specified, an Anchor object is also created:

<a href="url"                  // The destination of the link
    [ name="anchor_tag" ]      // Creates an Anchor object
    [ target="window_name" ]   // Where the new document should be displayed
    [ onclick="handler" ]      // Invoked when link is clicked
    [ onmouseover="handler" ]  // Invoked when mouse is over link
    [ onmouseout="handler" ]   // Invoked when mouse leaves link
>
link text or image             // The visible part of the link
</a>

In JavaScript 1.1 and later, a Link object is also created by each <area> tag within a client-side image map. This is also standard HTML:

<map name="map_name">
    <area shape="area_shape"
        coords="coordinates"
        href="url"                 // The destination of the link
        [ target="window_name" ]   // Where the new document should be displayed
        [ onclick="handler" ]      // Invoked when area is clicked
        [ onmouseover="handler" ]  // Invoked when mouse is over area
        [ onmouseout="handler" ]   // Invoked when mouse leaves area
>
    ...
</map>

Description

The Link object represents a hypertext link or a clickable area of a client-side image map in an HTML document. All links created with the <a> and <area> tags are represented by Link objects and stored in the links[] array of the Document object. Note that links created by both the <a> and <area> tags are stored in the same array -- there is no distinction between them.

The destination of a hypertext link is a URL, of course, and many of the properties of the Link object specify the contents of that URL. The Link object is similar to the Location object, which also has a full set of URL properties. In the case of the Location object, these properties describe the URL of the currently displayed document.

In addition to its properties, the Link object has three event handlers. The onmouseover( ), onclick( ), and onmouseout( ) event handlers specify code to be executed when the mouse passes over the hypertext link, clicks on it, and moves off or out of the link's region of the screen.

See Also

Anchor, Location; HTMLAnchorElement in the DOM reference section

Link.onclickthe handler invoked when a Link is clicked

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

<a ... onclick="handler" ... >
<area ... onclick="handler" ... >
link.onclick

Description

The onclick property of a Link object specifies an event handler function that is invoked when the user clicks on the link. The initial value of this property is a function that contains the JavaScript statements specified by the onclick attribute of the <a> or <area> tag that defined the Link object. When an event handler function is defined in this way by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

The onclick event handler is invoked before the browser follows the clicked hypertext link. This allows you to dynamically set href, target, and other properties of the link (using the this keyword to refer to the clicked link). You may also use the methods Window.alert( ), Window.confirm( ), and Window.prompt( ) from this event handler.

In JavaScript 1.1, you may prevent the browser from following the link by returning false. If you return true, any other value, or nothing, the browser follows the link as soon as onclick returns. You might stop the browser from following a link if you use the Window.confirm( ) method to ask the user if he really wants to follow the link and the user chooses the Cancel button, for example. In general, if you want a link that performs some action but does not cause a new URL to be displayed, it is better to use the onclick event handler of a Button object instead of the onclick handler of a Link object.

Note that while the onclick event handler returns false to tell the browser not to perform its default action (following a link), the onmouseover event handler must return true to tell the browser not to take its default action (displaying the URL of the link). This incompatibility exists for historical reasons. The standard for Form and form element event handlers is to return false to prevent the browser from performing a default action.

In the Netscape 4 event model, the onclick handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the hypertext link.

Bugs

In Netscape 3, the onclick event handler of the <area> does not work on Windows platforms. A workaround is to specify a javascript: URL as the value of the href attribute of the <area> tag.

See Also

Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Link.onmouseoutthe handler invoked when the mouse leaves a link

Availability

JavaScript 1.1

Synopsis

<a ... onmouseout="handler" ... >
<area ... onmouseout="handler" ...
> link.onmouseout

Description

The onmouseout property of a Link object specifies an event handler function that is invoked when the user moves the mouse off a hypertext link. The initial value of this property is a function that contains the JavaScript statements specified by the onmouseout attribute of the <a> or <area> tag that defined the Link object. When an event handler function is defined in this way by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onmouseout handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the hypertext link.

See Also

Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Link.onmouseoverthe handler invoked when the mouse goes over a link

Availability

JavaScript 1.0

Synopsis

<a ... onmouseover="handler" ... >
<area ... onmouseover="handler" ...
> link.onmouseover

Description

The onmouseover property of a Link object specifies an event handler function that is invoked when the user moves the mouse over a hypertext link. The initial value of this property is a function that contains the JavaScript statements specified by the onmouseover attribute of the <a> or <area> tag that defined the Link object. When an event handler function is defined in this way by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

By default, the browser displays the URL that a hypertext link refers to in the status line whenever the mouse goes over the link. The onmouseover event handler is invoked before the URL is displayed. If the handler returns true, the browser does not display the URL. Thus, an event handler function that returns true can display a custom message in the status line by setting the Window.status property to any desired value.

Note that while this event handler returns true to tell the browser not to perform its default action (displaying the URL of a link), the onclick event handler of the Link object must return false to tell the browser not to take its default action (following the link). This incompatibility exists for historical reasons. The standard for Form and form element event handlers is to return false to prevent the browser from performing a default action.

In the Netscape 4 event model, the onmouseover handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the hypertext link.

See Also

Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Link.targetthe target window of a hypertext link

Availability

JavaScript 1.0

Synopsis

link.target 

Description

target is a read/write string property of the Link object. It specifies the name of the frame or window in which the URL referred to by the Link object should be displayed. The initial value of this property is specified by the target attribute of the <a> tag that creates the Link object. If this attribute is unset, the default is that the window containing the link is used, so following a hypertext link overwrites the document that contains the link.

Note that the value of target is the name of a frame or window, not an actual JavaScript reference to the frame or window itself. The name of a frame is specified by the name attribute of the <frame> tag. The name of a window is specified when the window is created with a call to the Window.open( ) method. If target specifies the name of a window that does not exist, the browser automatically opens a new window to display the URL, and any future links with the same target name use that freshly created window.

Four special target names are supported. The target named "_blank" specifies that a new, empty browser window should be created and used to display the new URL. The target "_self" is the default; it specifies that the new URL should be displayed in the same frame or window as the link. The target "_parent" specifies that the results should be displayed in the parent frame of the frame that contains the link. Finally, the "_top" target specifies that the new URL should be displayed in the topmost frame -- in other words, all frames should be removed, and the new URL should occupy the entire browser window.

See Also

Form.target

Locationrepresents and controls browser location

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

location 
window.location 

Properties

The properties of a Location object refer to the various portions of the current document's URL. In each of the following property descriptions, the example given is a portion of this (fictitious) URL:

http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results
hash
A read/write string property that specifies the anchor portion of the URL, including the leading hash (#) mark. For example: "#result". This portion of the document URL specifies the name of an anchor within the document.

host
A read/write string property that specifies the hostname and port portions of the URL. For example, "www.oreilly.com:1234".

hostname
A read/write string property that specifies the hostname portion of a URL. For example "www.oreilly.com".

href
A read/write string property that specifies the complete text of the document's URL, unlike other Location properties which specify only portions of the URL. Setting this property to a new URL causes the browser to read and display the contents of the new URL.

pathname
A read/write string property that specifies the pathname portion of a URL. For example "/catalog/search.html".

port
A read/write string (not a number) property that specifies the port portion of a URL. For example "1234".

protocol
A read/write string property that specifies the protocol portion of a URL, including the trailing colon. For example, "http:".

search
A read/write string property that specifies the query portion of a URL, including the leading question mark. For example, "?q=JavaScript&m=10".

Methods

reload( )
Reloads the current document from the cache or the server. This method was added in JavaScript 1.1.

replace( )
Replaces the current document with a new one without generating a new entry in the browser's session history. This method was added in JavaScript 1.1.

Description

The Location object is stored in the location property of the Window object and represents the web address (the "location") of the document currently displayed in that window. The href property contains the complete URL of that document, and the other properties of the Location object each describe a portion of that URL. These properties are much like the URL properties of the Link object.

While the Link object represents a hyperlink in a document, the Location object represents the URL, or location, currently displayed by the browser. But the Location object does more than that: it also controls the location displayed by the browser. If you assign a string containing a URL to the Location object or to its href property, the web browser responds by loading the newly specified URL and displaying the document it refers to.

Instead of setting location or location.href to replace the current URL with a completely new one, you can also modify just a portion of the current URL by assigning strings to the other properties of the Location object. This creates a new URL with one new portion, which the browser loads and displays. For example, if you set the hash property of the Location object, you can cause the browser to move to a named location within the current document. Similarly, if you set the search property, you can cause the browser to reload the current URL with a new query string appended. If the URL refers to a server-side program, the document resulting from the new query string may be quite different from the original document.

In addition to its URL properties, the Location object also defines two methods. The reload( ) method reloads the current document, and the replace( ) method loads a new document without creating a new history entry for it -- the new document replaces the current one in the browser's history list.

See Also

Link, the location property of the Window object

Location.reload( )reload the current document

Availability

JavaScript 1.1

Synopsis

location.reload( ) 
location.reload(force)

Arguments

force
A boolean argument that specifies whether the document should be reloaded, even if the server reports that it has not been modified since it was last loaded. If this argument is omitted, or if it is false, the method reloads the full page only if it has changed since last loaded.

Description

The reload( ) method of the Location object reloads the document that is currently displayed in the window of the Location object. When called with no arguments or with the argument false, it uses the If-Modified-Since HTTP header to determine whether the document has changed on the web server. If the document has changed, reload reloads the document from the server, and if not, it reloads the document from the cache. This is the same action that occurs when the user clicks on the browser's Reload button.

When reload( ) is called with the argument true, it always bypasses the cache and reloads the document from the server, regardless of the last-modified time of the document. This is the same action that occurs when the user Shift-clicks on the browser's Reload button.

Location.replace( )replace one displayed document with another

Availability

JavaScript 1.1

Synopsis

location.replace(url)

Arguments

url
A string that specifies the URL of the new document that is to replace the current one.

Description

The replace( ) method of the Location object loads and displays a new document. Loading a document in this way is different from simply setting location or location.href in one important respect: the replace( ) method does not generate a new entry in the History object. When you use replace( ), the new URL overwrites the current entry in the History object. After calling replace( ), the browser's Back button does not return you to the previous URL; it returns you to the URL before that one.

Usage

When you are working with multiple frames and/or JavaScript-generated documents, you sometimes end up with quite a few temporary documents. If there are more than just a few of these documents, backing out of your web site with the Back button can be annoying. If you use the replace( ) method to load these documents, however, you can prevent this problem.

See Also

History

MimeTyperepresents a MIME data type

Availability

Netscape 3

Synopsis

navigator.mimeTypes[i]
navigator.mimeTypes["type"]
navigator.mimeTypes.length

Properties

description
A read/only string that provides a human-readable description (in English) of the data type described by the MimeType. This description is more explicit and understandable than the name property.

enabledPlugin
A read-only reference to a Plugin object that represents the installed and enabled plugin that handles the specified MIME type. If the MIME type is not handled by any plugins, the value of this property is null.

The navigator.mimeType[] array tells you whether a given MIME type is supported by the browser. The enabledPlugin property of the MimeType object, however, tells you whether a particular supported type is supported with a plugin (MIME types can also be supported with helper applications, or directly by the browser). If a MIME type is supported by a plugin, data of that type can be embedded in a web page with the <embed> tag.

suffixes
A read-only string that contains a comma-separated list of filename suffixes (not including the "." character) that are commonly used with files of the specified MIME type. For example, the suffixes for the text/html MIME type are "html, htm".

type
A read-only string that specifies the name of the MIME type. This is a unique string such as "text/html" or "image/jpeg" that distinguishes this MIME type from all others. It describes the general type of data and the data format used. The value of the type property can also be used as an index to access the elements of the navigator.mimeTypes[] array.

Description

The MimeType object represents a MIME type (i.e., a data format) supported by Netscape. The format may be supported directly by the browser or through an external helper application or a plugin for embedded data.

Usage

The navigator.mimeTypes[] array may be indexed numerically or with the name of the desired MIME type (which is the value of the type property). To check which MIME types are supported by Netscape, you can loop through each element in the array numerically. Or, if you just want to check whether a specific type is supported, you can write code like the following:

var show_movie = (navigator.mimeTypes["video/mpeg"] != null); 

See Also

Navigator, Plugin

Navigatorinformation about the browser in use

Availability

JavaScript 1.0; enhanced in JavaScript 1.1 and 1.2

Synopsis

navigator 

Properties

appCodeName
A read-only string that specifies the code name of the browser. In all Netscape browsers, this is "Mozilla". For compatibility, this property is "Mozilla" in Microsoft browsers as well.

appName
A read-only string property that specifies the name of the browser. For Netscape, the value of this property is "Netscape". In IE, the value of this property is "Microsoft Internet Explorer".

appVersion
A read-only string that specifies version and platform information for the browser. The first part of this string is a version number. Pass the string to parseInt( ) to obtain only the major version number or to parseFloat( ) to obtain the major and minor version numbers as a floating-point value. The remainder of the string value of this property provides other details about the browser version, including the operating system it is running on. Unfortunately, however, the format of this information varies widely from browser to browser.

cookieEnabled[IE 4, Netscape6]
A read-only boolean that is true if the browser has cookies enabled and false if they are disabled.

language [Netscape 4]
A read-only string that specifies the default language of the browser version. The value of this property is either a standard two-letter language code, such as "en" for English or "fr" for French, or a five-letter string that indicates a language and a regional variant, such as "fr_CA" for French, as spoken in Canada. Note that IE 4 provides two different language-related properties.

mimeTypes[] [Netscape 3]
An array of MimeType objects, each of which represents one of the MIME types (e.g., "text/html" and "image/gif") supported by the browser. The mimeTypes[] array is defined by IE 4 but is always empty because IE 4 does not support the MimeType object.

platform [ JavaScript 1.2]
A read-only string that specifies the operating system and/or hardware platform on which the browser is running. Although there is no standard set of values for this property, some typical values are "Win32", "MacPPC", and "Linux i586".

plugins[] [Netscape 3]
An array of Plugin objects, each of which represents one plugin that was installed with the browser. The Plugin object provides information about the plugin, including a list of MIME types it supports. A plugin is the Netscape name for a software package that is invoked by the browser to display specific data types within the browser window.

The plugins[] array is defined by IE 4 but is always empty because IE 4 does not support plugins or the Plugin object.

systemLanguage [IE 4]
A read-only string that specifies the default language of the operating system using the same standard codes used by the Netscape-specific language property.

userAgent
A read-only string that specifies the value the browser uses for the user-agent header in HTTP requests. Typically, this is the value of navigator.appCodeName followed by a slash and the value of navigator.appVersion. For example:

Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)
userLanguage [IE 4]
A read-only string that specifies the user's preferred language using the same standard codes used by the Netscape-specific language property.

Functions

navigator.javaEnabled( )
Tests whether Java is supported and enabled in the current browser. Added in JavaScript 1.1.

navigator.plugins.refresh( )
Checks for newly installed plugins, enters them in the plugins[] array, and optionally reloads documents using those plugins. Added in Netscape 3.

Description

The Navigator object contains properties that describe the web browser in use. You can use its properties to perform platform-specific customization. The name of this object obviously refers to the Netscape Navigator browser, but other browsers that implement JavaScript support this object as well.

There is only a single instance of the Navigator object, which you can reference through the navigator property of any Window object. Because of the implicit window reference, you can always refer to the Navigator object simply as navigator.

See Also

MimeType, Plugin

Navigator.javaEnabled( )test whether Java is available

Availability

JavaScript 1.1

Synopsis

navigator.javaEnabled( ) 

Returns

true if Java is supported by and enabled on the current browser; false otherwise.

Description

You can use navigator.javaEnabled( ) to check whether the current browser supports Java and can therefore display applets.

Navigator.plugins.refresh( )make newly installed plugins available

Availability

Netscape 3

Synopsis

navigator.plugins.refresh([reload])

Arguments

reload
An optional boolean argument that, if true, specifies that refresh( ) should reload any pages that contain <embed> tags and use plugins. Defaults to false if omitted.

Description

The refresh( ) method causes Netscape to check whether any new plugins have been installed. If so, the plugins[] array is updated ("refreshed") to include the newly installed plugins. If the reload argument is specified and is true, Netscape also reloads any currently displayed documents that contain <embed> tags and use plugins.

Note the unusual synopsis for this method. refresh( ) is a method of the plugins[] array, not of the Navigator object. For almost all purposes, however, it is simpler to consider it a method of the Navigator object, which is why it is grouped here with the methods and properties of that object.

Optionan option in a Select box

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

select.options[i]

Constructor

In JavaScript 1.1, Option objects can be dynamically created with the Option( ) constructor, as follows:

new Option(text, value, defaultSelected, selected)

Arguments

text
An optional string argument that specifies the text property of the Option object.

value
An optional string argument that specifies the value property of the Option object.

defaultSelected
An optional boolean argument that specifies the defaultSelected property of the Option object.

selected
An optional boolean argument that specifies the selected property of the Option object.

Properties

Option inherits the properties of HTMLElement and defines the following:

defaultSelected
A boolean that specifies whether the option is initially selected when the Select object that contains it is created. This value is used to restore a Select object to its initial state when the containing form is reset. The initial value of this property is specified by the selected attribute of the <option> tag.

index
A read-only integer that specifies the position or index of the option within the options[] array of the Select object that contains it. The first Option object in the array has its index property set to 0. The second Option has an index of 1, and so on.

selected
A read/write boolean value that specifies whether an option is currently selected. You can use this property to test whether a given option is selected and to select (by setting it to true) or deselect (by setting it to false) a given option. Note that when you select or deselect an option in this way the Select.onchange( ) event handler is not invoked.

text
A string that specifies the text for the option that appears to the user. The initial value of this property is whatever plain text (without HTML tags) appears after the <option> tag and before the next <option>, </option>, or </select> tag.

In JavaScript 1.0, the text property is read-only. In JavaScript 1.1, it is read/write. By setting a new value for this property, you can change the text that appears for the option within its Select object. Note that if you plan to set this property in a browser that cannot reflow document content, you should ensure that changing the option label does not make the Select object wider. If the object must become wider, ensure that no information to the right of the Select object becomes obscured when it grows.

value
A read/write string that specifies the text passed to the web server if the option is selected when the form is submitted. The initial value of value is specified by the value attribute of the <option> tag. If the form is designed to be submitted to a server (as opposed to simply being used by JavaScript on the client side), each Option object within a Select object should have a distinct value.

HTML Syntax

An Option object is created by an <option> tag within a <select>, which is within a <form>. Multiple <option> tags typically appear within the <select>:

<form ...>
  <select  ...>
    <option
        [ value="value" ]  // The value returned when the form is submitted
        [ selected ] >     // Specifies whether this option is initially selected
    plain_text_label       // The text to display for this option
    [ </option> ]
        ...
  </select>
        ...
</form>

Description

The Option object describes a single option displayed within a Select object. The properties of this object specify whether it is selected by default, whether it is currently selected, the position it has in the options[] array of its containing Select object, the text it displays, and the value it passes to the server if it is selected when the containing form is submitted.

Note that although the text displayed by this option is specified outside of the <option> tag, it must be plain, unformatted text without any HTML tags so it can be properly displayed in list boxes and drop-down menus that do not support HTML formatting.

In JavaScript 1.1, you can dynamically create new Option objects for display in a Select object with the Option( ) constructor. Once a new Option object is created, it can be appended to the list of options in a Select object s by assigning it to:

s.options[options.length] 

See the Select.options[] reference page for details.

See Also

Select, Select.options[]; HTMLOptionElement and HTMLSelectElement in the DOM reference section

Passworda text input field for sensitive data

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i]

Properties

Password inherits properties from Input and HTMLElement and defines or overrides the following:

value
A read/write string that specifies the password entered by the user. It is the value sent over the Net when the form is submitted. The initial value of this property is specified by the value attribute of the <input> element that defined the Password object. Note that because of the sensitive nature of password input, security restrictions may protect the value property. In some browsers, the string returned when querying this property may not match the text entered by the user, and setting the property may have no effect on either the displayed value or the value submitted upon form submission.

Methods

Password inherits methods from Input and HTMLElement.

Event Handlers

Password inherits event handlers from Input and HTMLElement.

HTML Syntax

A Password element is created with a standard HTML <input> tag:

<form>
    ...
  <input
    type="password"      // Specifies that this is a Password element
    [ name="name" ]      // A name you can use later to refer to this element
                         // Specifies the name property
    [ value="default" ]  // The default value transmitted when the form is submitted
    [ size="integer" ]   // How many characters wide the element is
  >
    ...
</form> 

Description

The Password element is a text input field intended for input of sensitive data, such as passwords. As the user types characters, only asterisks appear. This prevents bystanders from reading the input value over the user's shoulder. As a further security precaution, there are limitations on how JavaScript can read and write the value property of a Password element. See the Text and Input reference pages for more information.

See Also

Input, Text; HTMLInputElement in the DOM reference section

Plugindescribes an installed plugin

Availability

Netscape 3

Synopsis

navigator.plugins[i]
navigator.plugins['name']

Properties

description
A read-only string that contains a human-readable description of the specified plugin. The text of this description is provided by the creators of the plugin and may contain vendor and version information as well as a brief description of the plugin's function.

filename
A read-only string that specifies the name of the file on disk that contains the plugin program itself. This name may vary from platform to platform. The name property is more useful than filename for identifying a plugin.

length
Each Plugin object contains MimeType array elements that specify the data formats supported by the plugin. As with all arrays, the length property specifies the number of elements in the array.

name
The name property of a Plugin object is a read-only string that specifies the name of the plugin. Each plugin should have a name that uniquely identifies it. The name of a plugin can be used as an index into the navigator.plugins[] array. You can use this fact to determine easily whether a particular named plugin is installed in the current browser:

var sw_installed = (navigator.plugins["Shockwave"] != null);

Elements

The array elements of the Plugin object are MimeType objects that specify the data formats supported by the plugin.

Description

A plugin is a software module that can be invoked by Netscape to display specialized types of embedded data within the browser window. In Netscape 3, plugins are represented by the Plugin object. This object is somewhat unusual in that it has both regular object properties and array elements. The properties of the Plugin object provide various pieces of information about the plugin, and its array elements are MimeType objects that specify the embedded data formats that the plugin supports.

Plugin objects are obtained from the plugins[] array of the Navigator object. navigator.plugins[] may be indexed numerically when you want to loop through the complete list of installed plugins, looking for one that meets your needs (for example, one that supports the MIME type of the data you want to embed in your web page). This array can also be indexed by plugin name, however. That is, if you want to check whether a specific plugin is installed in the user's browser, you might use code like this:

document.write( navigator.plugins("Shockwave") ?
                "<embed src="movie.dir' height=100 width=100>" :
                "You don't have the Shockwave plugin!" ); 

The name used as an array index with this technique is the same name that appears as the value of the name property of the Plugin.

Don't confuse the fact that Plugin objects are stored in an array of the Navigator object with the fact that each Plugin object is itself an array of MimeType objects. Because there are two arrays involved, you may end up with code that looks like this:

navigator.plugins[i][j]            // The jth MIME type of the ith plugin
navigator.plugins["LiveAudio"][0]  // First MIME type of LiveAudio plugin 

Finally, note that while the array elements of a Plugin object specify the MIME types supported by that plugin, you can also determine which plugin supports a given MIME type with the enabledPlugin property of the MimeType object.

See Also

Navigator, MimeType

Radioa graphical radio button

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

The Radio button element is usually used in groups of mutually exclusive options that have the same name. To reference one Radio element within a group, use this syntax:

form.radio_name[j]
form.radio_name.length 

Properties

Radio inherits properties from Input and HTMLElement and defines or overrides the following:

checked
A read/write boolean that is true if the radio button is checked or false otherwise. If you set checked to true, the radio button is selected, and the previously selected button is deselected. Note, however, that setting the checked property of a radio button to false has no effect, because at least one button must always be selected; you cannot deselect a radio button except by selecting some other button. Note also that setting the checked property does not cause the Radio button element's onclick event handler to be invoked. If you want to invoke that event handler, you must do so explicitly.

defaultChecked
A boolean property that is true if the radio button is initially selected, but only if the checked attribute appears in the button's HTML <input> tag. If this tag does not appear, the radio button is initially deselected, and defaultChecked is false.

value
A read/write string that specifies the text passed to the web server if the radio button is checked when the form is submitted. The initial value of this property is specified by the value attribute of the button's <input> tag. If the form is designed to be submitted to a server (as opposed to simply being used by JavaScript on the client side), each radio button in a group should have a distinct value. Note that the value field does not specify whether the radio button is currently selected; the checked property specifies the current state of the Radio object.

Methods

Radio inherits methods from Input and HTMLElement.

Event Handlers

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

onclick
Invoked when the radio button is clicked.

HTML Syntax

A Radio element is created with a standard HTML <input> tag. Radio elements are created in groups by specifying multiple <input> tags that have the same name attribute:

<form>
    ...
  <input
    type="radio"           // Specifies that this is a radio button

    [ name="name" ]        // A name you can use later to refer to this button
                           // or to the group of buttons with this name
                           // Specifies the name property
    [ value="value" ]      // The value returned when this button is selected
                           // Specifies the value property
    [ checked ]            // Specifies that the button is initially checked
                           // Specifies the defaultChecked property
    [ onclick="handler" ]  // JavaScript statements to be executed when the button
                           // is clicked
  >
label                      // The HTML text that should appear next to the button
    ...
</form> 

Description

The Radio element represents a single graphical radio button in an HTML form. A radio button is one button in a group of buttons that represents mutually exclusive choices. When one button is selected, the previously selected button is deselected. The onclick event handler allows you to specify JavaScript code to be executed when the button is selected.

You can examine the checked property to determine the state of the button and set this property to select or deselect the button. Note that setting checked changes the graphical appearance of the button but does not invoke the onclick event handler. The initial value of the checked property and the value of the defaultChecked property are determined by the checked attribute. Only one Radio element in a group may contain this attribute -- it sets the checked and defaultChecked properties true for that element and false for all other radio buttons in the group. If none of the elements has the checked attribute, the first one in the group is checked (and defaultChecked) by default.

Note that the text that appears next to a radio button is not part of the Radio element itself and must be specified externally to the Radio's HTML <input> tag.

Radio elements are used in groups of mutually exclusive options. A mutually exclusive group is defined as the set of all Radio elements within a form that have the same name. If the shared name of a group of Radio elements in form f is opts, f.opts is an array of Radio elements, and f.opts.length is the number of elements in the array.

You can set the value attribute or the value property of a Radio element to specify the string that is passed to the server if the Radio element is checked when the form is submitted. Each Radio element in a group should specify a distinct value so a script on the server can determine which one was checked when the form was submitted.

Usage

Radio elements can present the user with a list of multiple mutually-exclusive options. Use the Checkbox element to present a single option or a list of options that are not mutually exclusive.

See Also

Checkbox, Form, Input; HTMLInputElement in DOM reference section

Radio.onclickthe handler invoked when a radio button is selected

Availability

JavaScript 1.0

Synopsis

<input type="radio" onclick="handler"... > 
radio.onclick

Description

The onclick property of a Radio object refers to an event handler function that is invoked when the user clicks on the checkbox. See the HTMLElement.onclick reference page for complete details. Note, however, that Radio.onclick has been supported since JavaScript 1.0, unlike the generalized HTMLElement.onclick handler.

See Also

HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Reseta button to reset a form's values

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i]

Properties

Reset inherits properties from Input and HTMLElement and defines or overrides the following:

value
A string that specifies the text that appears within the Reset button. It is specified by the value attribute of the <input> tag that created the button. If no value attribute is specified, the default value is "Reset" (or the equivalent in the browser's default language). In browsers that cannot reflow document content, this property may be read-only.

Methods

Reset inherits the methods of Input and HTMLElement.

Event Handlers

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

onclick
Invoked when the Reset button is clicked.

HTML Syntax

A Reset element is created with a standard HTML <input> tag:

<form>
    ...
  <input
    type="reset"           // Specifies that this is a Reset button
    [ value="label" ]      // The text that is to appear within the button
                           // Specifies the value property
    [ name="name" ]        // A name you can use later to refer to the button
                           // Specifies the name property
    [ onclick="handler" ]  // JavaScript statements to be executed when the button
                           // is clicked
  >
    ...
</form> 

Reset objects can also be created with the HTML 4 <button> tag:

<button id="name"
        type="reset"
        onclick="handler">
label
</button>

Description

The Reset element has the same properties and methods as the Button element but has a more specialized purpose. When a Reset element is clicked, the values of all input elements in the form that contains it are reset to their initial default values. (For most elements, this means to the value specified by the HTML value attribute.) If no initial value was specified, a click on the Reset button clears any user input from those elements.

Usage

If no value attribute is specified for a Reset element, it is labeled "Reset". In some forms, it may be better to label the button "Clear Form" or "Defaults".

In JavaScript 1.1, you can simulate the action of a Reset button with the reset( ) method of the Form object. Also in JavaScript 1.1, the onreset event handler of the Form object is invoked before the form is reset. This event handler can cancel the reset by returning false.

See Also

Button, Form, HTMLElement, Input; HTMLInputElement in the DOM reference section

Reset.onclickthe handler invoked when a Reset button is clicked

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

<input type="reset" onclick="handler" ... > 
reset.onclick

Description

The onclick property of a Reset object refers to an event handler function that is invoked when the user clicks on the Reset button. See the HTMLElement.onclick reference page for complete details. Note, however, that Reset.onclick has been supported since JavaScript 1.0, unlike the generalized HTMLElement.onclick handler.

The Reset button has the special function of resetting all form elements to their default value. The onclick event handler may add any additional functionality to the Reset button. In JavaScript 1.1, the onclick handler may return false to prevent the Reset object from resetting the form. (For example, the onclick handler could use confirm( ) to ask the user to confirm the reset and return false if it was not confirmed.)

See Also

Form.onreset, Form.reset( ), HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Screenprovides information about the display

Availability

JavaScript 1.2

Synopsis

screen

Properties

availHeight
Specifies the available height, in pixels, of the screen on which the web browser is displayed. On operating systems such as Windows, this available height does not include vertical space allocated to semipermanent features, such as the task bar at the bottom of the screen.

availLeft [Netscape 4]
Specifies the leftmost X-coordinate that is not allocated to a semipermanent display feature, such as an application shortcut bar or the Windows 95 task bar.

availTop [Netscape 4]
Specifies the topmost Y-coordinate that is not allocated to a semipermanent display feature, such as an application shortcut bar or the Windows 95 task bar.

availWidth
Specifies the available width, in pixels, of the screen on which the web browser is displayed. On operating systems such as Windows, this available width does not include horizontal space allocated to semipermanent features, such as application shortcut bars.

colorDepth
Specifies the base-2 logarithm of the number of colors allocated by the web browser and available for displaying images. For example, if a browser preallocates 128 colors, screen.colorDepth would be 7. On systems that do not allocate color palettes, this value is the same as the number of bits-per-pixel for the screen.

In IE 4, colorDepth specifies the color depth of the screen in bits-per-pixel, rather than the depth of a preallocated color palette. The screen.pixelDepth property provides this value in Netscape.

height
Specifies the total height, in pixels, of the screen on which the web browser is displayed. See also availHeight.

pixelDepth [Netscape 4]
Specifies the color depth, in bits-per-pixel, of the screen on which the web browser is displayed. Contrast with colorDepth.

width
Specifies the total width, in pixels, of the screen on which the web browser is displayed. See also availWidth.

Description

The screen property of every Window refers to a Screen object. The static properties of this global object contain information about the screen on which the browser is displayed. JavaScript programs can use this information to optimize their output to match the user's display capabilities. For example, a program can choose between large and small images based on the display size and between 16-bit color images and 8-bit color images based on the screen's color depth. A JavaScript program can also use the information about the size of the screen to center new browser windows on the screen.

See Also

The screen property of the Window object

Selecta graphical selection list

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.element_name 
form.elements[i]

Properties

Select inherits properties from Input and HTMLElement and defines or overrides the following:

length
A read-only integer that specifies the number of elements in the options[] array. The value of this property is the same as options.length.

options
An array of Option objects, each of which describes one of the options displayed within the Select element. See the Select.options[] reference page for details about this array, including techniques for modifying the options displayed by the Select object.

selectedIndex
An integer that specifies the index of the selected option within the Select object. If no option is selected, selectedIndex is -1. If more than one option is selected, selectedIndex specifies the index of the first one only.

In JavaScript 1.0, selectedIndex is a read-only property. In JavaScript 1.1, it is read/write. Setting the value of this property selects the specified option and deselects all other options, even if the Select object has the multiple attribute specified. When you're doing list-box selection (instead of drop-down menu selection), you can deselect all options by setting selectedIndex to -1. Note that changing the selection in this way does not trigger the onchange( ) event handler.

type [ JavaScript 1.1]
A read-only string property shared by all form elements; it specifies the type of the element. The Select object is unusual in that there are two possible values for the type property. If the Select object allows only a single selection (i.e., if the multiple attribute does not appear in the object's HTML definition), the value of the type property is "select-one". If the multiple attribute does appear, the value of the type attribute is "select-multiple". See also the Input.type reference page.

Methods

Select inherits the methods of Input and HTMLElement.

Event Handlers

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

onchange
Invoked when the user selects or deselects an item.

HTML Syntax

A Select element is created with a standard HTML <select> tag. Options to appear within the Select element are created with the <option> tag:

<form>
    ...
<select
    name="name"  // A name that identifies this element; specifies name property
    [ size="integer" ]      // Number of visible options in Select element
    [ multiple ]            // Multiple options may be selected, if present
    [ onchange="handler" ]  // Invoked when the selection changes
>
<option value="value1" [selected]> option_label1
<option value="value2" [selected]> option_label2

// Other options here
</select>
   ...
</form>

Description

The Select element represents a graphical list of choices for the user. If the multiple attribute is present in the HTML definition of the element, the user may select any number of options from the list. If that attribute is not present, the user may select only one option, and options have a radio button behavior -- selecting one deselects whichever was previously selected.

The options in a Select element may be displayed in two distinct ways. If the size attribute has a value greater than 1, or if the multiple attribute is present, they are displayed in a list box which is size lines high in the browser window. If size is smaller than the number of options, the list box includes a scrollbar so all the options are accessible. On the other hand, if size is specified as 1 and multiple is not specified, the currently selected option is displayed on a single line, and the list of other options is made available through a drop-down menu. The first presentation style displays the options clearly but requires more space in the browser window. The second style requires minimal space but does not display alternative options as explicitly.

The options[] property of the Select element is the most interesting. This is the array of Option objects that describe the choices presented by the Select element. The length property specifies the length of this array (as does options.length). See the documentation of the Option object for details.

In JavaScript 1.1, the options displayed by the Select element may be dynamically modified. You can change the text displayed by an Option object simply by setting its text property. You can change the number of options displayed by the Select element by setting the options.length property. And you can create new options for display with the Option( ) constructor function. See the Select.options[] and Option reference pages for details.

Note that the Select object is a kind of Input object and inherits from Input, despite the fact that Select objects are not created with HTML <input> tags.

See Also

Form, HTMLElement, Input, Option; HTMLSelectElement in the DOM reference section

Select.onchangethe handler invoked when the selection changes

Availability

JavaScript 1.0

Synopsis

<select ... onchange="handler" ... > 
select.onchange

Description

The onchange property of a Select object refers to an event handler function that is invoked when the user selects or deselects an option. See the Input.onchange reference page for further details on this event handler.

See Also

Input.onchange, Option; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Select.options[]the choices in a Select object

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

select.options[i]
select.options.length

Description

The options[] property contains an array of Option objects, each of which describes one of the selection options presented within the Select object select. The options.length property specifies the number of elements in the array, as does the select.length property. See the Option object for further details.

In JavaScript 1.1, you can modify the options displayed in a Select object in any of the following ways:

See Also

Option

StyleCascading Style Sheet attributes

Availability

Internet Explorer 4, Netscape 6

Synopsis

htmlElement.style 

Properties

The Style object has properties corresponding to each of the CSS attributes supported by the browser.

Description

The properties of the Style object correspond directly to the CSS attributes supported by the browser. For compatibility with JavaScript syntax, however, hyphenated CSS attribute names are written with mixed capitalization with the hyphen removed. So, for example, the CSS color attribute is represented by the color property of the Style object, while the CSS background-color attribute is represented by the backgroundColor property of the Style object. See Chapter 18 for more information about element styles.

See Also

{XREF}; Chapter 18; CSSStyleDeclaration and CSS2Properties in the DOM reference section.

Submita button to submit a form

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i] 
form.elements['name']

Properties

Submit inherits properties from Input and HTMLElement and defines or overrides the following:

value
A read-only string that specifies the text that appears within the Submit button. It is specified by the value attribute of the <input> tag that created the button. If no value attribute is specified, the default value is "Submit Query" or some similar string in the browser's default language. In browsers that cannot reflow document content, this property may be read-only.

Methods

Submit inherits methods from Input and HTMLElement.

Event Handlers

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

onclick
Invoked when the Submit button is clicked.

HTML Syntax

A Submit object is created with a standard HTML <input> tag:

<form>
    ...
  <input
    type="submit"          // Specifies that this is a Submit button
    [ value="label" ]      // The text that is to appear within the button
                           // Specifies the value property
    [ name="name" ]        // A name you can use later to refer to the button
                           // Specifies the name property
    [ onclick="handler" ]  // JavaScript statements to be executed when the button 
                           // is clicked
  >
    ...
</form>

Submit objects can also be created with the HTML 4 <button> tag:

<button id="name"
        type="submit"
        value="value"
        onclick="handler">label
</button>

Description

The Submit element has the same properties and methods as the Button object but has a more specialized purpose. When a Submit button is clicked, it submits the data in the form that contains the button to the server specified by the form's action attribute and loads the resulting HTML page sent back by that server. In JavaScript 1.1, the exception is that the form is not submitted if either the Submit.onclick or Form.onsubmit event handler returns false.

Note that in JavaScript 1.1 the Form.submit( ) method provides an alternative way to submit a form.

If no value attribute is specified for a Submit object, it is typically labeled "Submit Query". In some forms, it may make more sense to label the button "Submit", "Done", or "Send".

See Also

Button, Form.onsubmit, Form.submit( ), HTMLElement, Input; HTMLInputElement in the DOM reference section

Submit.onclickinvoked when a Submit button is clicked

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

<input type="submit" onclick="handler" ... > 
submit.onclick

Description

The onclick property of a Submit object refers to an event handler function that is invoked when the user clicks on the Submit button. See the HTMLElement.onclick reference page for complete details. Note, however, that Submit.onclick has been supported since JavaScript 1.0, unlike the generalized HTMLElement.onclick handler.

The Submit button has the special function of submitting the form to a server. The onclick event handler may add any additional functionality to the Submit button. In JavaScript 1.1 the onclick handler may return false to prevent the Submit object from submitting the form. (For example, the onclick handler could perform form validation and return false if required fields in the form are not filled in.)

See Also

Form.onsubmit, Form.submit( ), HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Texta graphical text input field

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i]

Properties

Text inherits properties from Input and HTMLElement and defines or overrides the following:

value
A read/write string that specifies the text displayed in the text input field. This text may have been entered by the user, or it may be a default value specified by the document or by a script. The initial value of this property is specified by the value attribute of the <input> tag that defines the Text object. When the user types characters into the Text object, the value property is updated to match the user's input. If you set the value property explicitly, the string you specify is displayed in the Text object. This property also specifies the string that is sent to the server when the form is submitted.

Methods

Text inherits the methods of Input and HTMLElement.

Event Handlers

Text inherits the event handlers of Input and HTMLElement and defines or overrides the following:

onchange
Invoked when the user changes the value in the Text element and moves the keyboard focus elsewhere. This event handler is not invoked for every keystroke in the Text element, but only when the user completes an edit.

HTML Syntax

A Text element is created with a standard HTML <input> tag:

<form>
    ...
  <input
    type="text"              // Specifies that this is a Text element
    [ name="name" ]          // A name you can use later to refer to this element
                             // Specifies the name property
    [ value="default" ]      // Default value transmitted when the form is submitted
                             // Specifies the defaultValue property
    [ size="integer" ]       // How many characters wide the element is
    [ maxlength="integer" ]  // Maximum allowed number of input characters
    [ onchange="handler" ]   // The onchange( ) event handler
  >
    ...
</form>

Description

The Text element represents a text input field in a form. The size attribute specifies the width, in characters, of the input field as it appears on the screen, and the maxlength attribute specifies the maximum number of characters the user is allowed to enter.

Besides these HTML attributes, value is the main property of interest for the Text element. You can read this property to obtain the user's input or set it to display arbitrary (unformatted) text in the input field.

Usage

Use the Password element instead of the Text element when the value you are asking the user to enter is sensitive information, such as a password that should not be displayed openly on the screen. Use a Textarea element to allow the user to enter multiple lines of text.

When a form contains only one Text or Password element, the form is automatically submitted if the user strikes the Return key in that Text or Password element. In many forms, this is a useful shortcut. In some, however, it can be confusing if the user strikes Return and submits the form before entering input into other form elements, such as Checkboxes and Radio buttons. You can sometimes minimize this confusion by placing Text elements with their default submission action at the bottom of the form.

See Also

Form, Input, Password, Textarea; HTMLInputElement in the DOM reference section

Text.onchangethe handler invoked when input value changes

Availability

JavaScript 1.0

Synopsis

<input type="text" onchange="handler" ... > 
text.onchange

Description

The onchange property of a Text element refers to an event handler function that is invoked when the user changes the value in the input field and then "commits" those changes by moving keyboard focus (i.e., by clicking the mouse elsewhere or pressing Tab or Return).

Note that the onchange event handler is not invoked when the value property of a Text object is set by JavaScript. Also note that this handler is intended to process a complete change to the input value, and therefore it is not invoked on a keystroke-by-keystroke basis. See the HTMLElement.onkeypress reference page for information on receiving notification of every key press event.

See Input.onchange for complete details about the onchange event handler.

See Also

HTMLElement.onkeypress, Input.onchange; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Textareaa multiline text input area

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i]

Properties

Textarea inherits the properties of Input and HTMLElement and defines or overrides the following:

value
A read/write string property. The initial value of this property is the same as the defaultValue property: the plain text (i.e., without any HTML tags) that appears between the <textarea> and </textarea> tags. When the user types characters into the Textarea object, the value property is updated to match the user's input. If you set the value property explicitly, the string you specify is displayed in the Textarea object. This value property contains the string that is sent to the server when the form is submitted.

Methods

Textarea inherits the methods of Input and HTMLElement.

Event Handlers

Textarea inherits the event handlers of Input and HTMLElement and defines or overrides the following:

onchange
Invoked when the user changes the value in the Textarea element and moves the keyboard focus elsewhere. This event handler is not invoked for every keystroke in the Textarea element, but only when the user completes an edit.

HTML Syntax

A Textarea element is created with standard HTML <textarea> and </textarea> tags:

<form>
    ...
  <textarea
    [ name="name" ]         // A name that can be used to refer to this element
    [ rows="integer" ]      // How many lines tall the element is
    [ cols="integer" ]      // How many characters wide the element is
    [ onchange="handler" ]  // The onchange( ) event handler
  >
    plain_text              // The initial text; specifies defaultValue
  </textarea>
    ...
</form>

Description

The Textarea element represents a text input field in a form. The name attribute specifies a name for the element. This is mandatory if the form is to be submitted, and it also provides a convenient way to refer to the Textarea element from JavaScript code. The cols attribute specifies the width, in characters, of the element as it appears on the screen, and the rows attribute specifies the height, in lines of text, of the element. The wrap attribute specifies how long lines should be handled: the value off specifies that they should be left as-is, the value virtual specifies that they should be displayed with line breaks but transmitted without them, and the value physical specifies that they should be displayed and transmitted with line breaks inserted.

In addition to these HTML attributes, value is the main property of interest for the Textarea element. You can read this property to obtain the user's input or set it to display arbitrary (unformatted) text in the Textarea. The initial value of the value property (and the permanent value of the defaultValue property) is the text that appears between the <textarea> and </textarea> tags.

Note that the Textarea object is a kind of Input object and inherits from Input, despite the fact that Textarea objects are not created with HTML <input> tags.

Usage

If you need only a single line of input text, use the Text element. If the text to be input is sensitive information, such as a password, use the Password element.

See Also

Form, HTMLElement, Input, Password, Text; HTMLTextAreaElement in the DOM reference section

Textarea.onchangethe handler invoked when input value changes

Availability

JavaScript 1.0

Synopsis

<textarea onchange="handler" ... >... </textarea> 
textarea.onchange

Description

The onchange property of a Textarea element refers to an event handler function that is invoked when the user changes the value in the text area and then "commits" those changes by moving keyboard focus elsewhere.

Note that the onchange event handler is not invoked when the value property of a Text object is set by JavaScript. Also note that this handler is intended to process a complete change to the input value, and therefore it is not invoked on a keystroke-by-keystroke basis. See the HTMLElement.onkeypress reference page for information on receiving notification of every key press event.

See Input.onchange for complete details about the onchange event handler.

See Also

HTMLElement.onkeypress, Input.onchange; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

URLsee Link, Location, or Document.URL

Windowa web browser window or frame

Availability

JavaScript 1.0; enhanced in JavaScript 1.1 and 1.2

Synopsis

self window window.frames[i]

Properties

The Window object defines the following properties. Nonportable, browser-specific properties are listed separately after this list.

closed
A read-only boolean value that specifies whether the window has been closed. When a browser window closes, the Window object that represents it does not simply disappear. The Window object continues to exist, but its closed property is set to true.

defaultStatus
A read/write string that specifies the default message that appears in the status line. See the Window.defaultStatus reference page.

document
A read-only reference to the Document object that describes the document contained in this window or frame. See the Document object for details.

frames[]
An array of Window objects, one for each frame contained within the this window. The frames.length property contains the number of elements in the frames[] array. Note that frames referenced by the frames[] array may themselves contain frames and may have a frames[] array of their own.

history
A read-only reference to the History object of this window or frame. See the History object for details.

length
The number of frames contained in this window or frame. length also specifies the number of elements in the frames[] array.

location
The Location object for this window or frame. This object specifies the URL of the currently loaded document. Setting this property to a new URL string causes the browser to load and display the contents of that URL. See the Location object for further details.

Math
A reference to an object holding various mathematical functions and constants. See the Math object for details.

name
A string that contains the name of the window. The name is optionally specified when the window is created with the open( ) method. Read-only in JavaScript 1.0; read/write in JavaScript 1.1. See the Window.name reference page.

navigator
A read-only reference to the Navigator object, which provides version and configuration information about the web browser. See the Navigator object for details.

opener [ JavaScript 1.1]
A read/write reference to the Window object that contained the script that called open( ) to open this top-level browser window. This property is valid only for Window objects that represent top-level windows, not those that represent frames. The opener property is useful so that a newly created window can refer to variables and functions defined in the window that created it.

parent
A read-only reference to the Window object that contains this window or frame. If this window is a top-level window, parent refers to the window itself. If this window is a frame, the parent property refers to the window or frame that contains it.

screen [ JavaScript 1.2]
The Screen object that is shared by all windows in a browser. This Screen object contains properties that specify information about the screen: the number of available pixels and the number of available colors. See the Screen object for details.

self
A read-only reference to this window itself. This is a synonym for the window property.

status
A read/write string that specifies the current contents of the browser's status line. See the Window.status reference page for details.

top
A read-only reference to the top-level window that contains this window. If this window is a top-level window itself, the top property simply contains a reference to the window itself. If this window is a frame, the top property refers to the top-level window that contains the frame. Contrast with the parent property.

window
The window property is identical to the self property; it contains a reference to this window.

Netscape Properties

innerHeight, innerWidth [Netscape 4]
Read/write properties that specify the height and width, in pixels, of the document display area of this window. These dimensions do not include the height of the menu bar, toolbars, scrollbars, and so on. As a security restriction, you are not allowed to set either of these properties to less than 100 pixels.

java [Netscape 3]
A reference to the JavaPackage object that is the top of the package name hierarchy for the core java.* packages that comprise the Java language. See the JavaPackage reference page.

locationbar.visible [Netscape 4]
A read-only boolean that specifies whether the window displays a location bar. See window features in the Window.open( ) reference page.

menubar.visible [Netscape 4]
A read-only boolean that specifies whether the window displays a menu bar. See window features in the Window.open( ) reference page.

netscape [Netscape 3]
A reference to the JavaPackage object which is the top of the Java package name hierarchy for the netscape.* Java packages from Netscape. See the JavaPackage reference page.

outerHeight, outerWidth [Netscape 4]
Read/write integers that specify the total height and width, in pixels, of the window. These dimensions include the height and width of the menu bar, toolbars, scrollbars, window borders, and so on.

Packages [Netscape 3]
A reference to a JavaPackage object that represents the top of the Java package name hierarchy. For example, use Packages.java.lang to refer to the java.lang package. See the JavaPackage reference page.

pageXOffset, pageYOffset [Netscape 4]
Read-only integers that specify the number of pixels that the current document has been scrolled to the right (pageXOffset) and down (pageYOffset).

personalbar.visible [Netscape 4]
A read-only boolean that specifies whether this window displays a "personal bar" of bookmarks. See window features in the Window.open( ) reference page.

screenX, screenY [Netscape 4]
Read-only integers that specify the X- and Y-coordinates of the upper-left corner of the window on the screen. If this window is a frame, these properties specify the X- and Y-coordinates of the top-level window that contains the frame.

scrollbars.visible [Netscape 4]
A read-only boolean that specifies whether the scroll bars are visible in this window, or would be visible if the document was long enough or wide enough to require them. What this property really specifies is whether scrolling is enabled in this window. See window features in the Window.open( ) reference page.

statusbar.visible [Netscape 4]
A read-only boolean that specifies whether this window has a status line. See window features in the Window.open( ) reference page.

sun [Netscape 3]
A reference to the JavaPackage object which is the top of the Java package name hierarchy for the sun.* Java packages from Sun Microsystems. See the JavaPackage reference page.

toolbar.visible [Netscape 4]
A read-only boolean that specifies whether this window displays a toolbar. See window features in the Window.open( ) reference page.

Internet Explorer Properties

clientInformation [IE 4]
An IE-specific synonym for the navigator property. Both refer to a Navigator object. Despite the fact that clientInformation has a better name and is less Netscape-specific than navigator, it is not supported by Netscape and is therefore not portable.

event [IE 4]
An Event object that contains the details of the most recent event to occur within window. In the Netscape 4 event model and the DOM standard event model, an Event object describing the event is passed as an argument to every event handler. In the IE event model, however, no Event object is passed, and event handlers must obtain information about the event from the event property of the Window object.

Methods

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

alert( )
Displays a simple message in a dialog box.

blur( )
Takes keyboard focus from the top-level browser window; this sends the window to the background on most platforms.

clearInterval( )
Cancels periodic execution of code.

clearTimeout( )
Cancels a pending timeout operation.

close( )
Closes a window.

confirm( )
Asks a yes-or-no question with a dialog box.

focus( )
Gives the top-level browser window keyboard focus; this brings the window to the front on most platforms.

moveBy( )
Moves the window by a relative amount.

moveTo( )
Moves the window to an absolute position.

open( )
Creates and opens a new window.

print( )
Simulates a click on the browser's Print button. IE 5 and Netscape 4 only.

prompt( )
Asks for simple string input with a dialog box.

resizeBy( )
Resizes the window by a specified amount.

resizeTo( )
Resizes the window to a specified size.

scroll( )
Scrolls the document displayed in the window.

scrollBy
Scrolls the window by a specified amount.

scrollTo( )
Scrolls the window to a specified position.

setInterval( )
Executes code at periodic intervals.

setTimeout( )
Executes code after a specified amount of time elapses.

Netscape Methods

back( )
Behaves as if the user clicked the Back button.

captureEvents( )
Specifies event types to be routed directly to the window.

forward( )
Simulates a click on the browser's Forward button.

handleEvent( )
Invokes the appropriate event handler for a given Event object.

home( )
Displays the browser's home page.

releaseEvents( )
Specifies types of events that will no longer be captured.

routeEvent( )
Passes an Event to the appropriate handler of the next interested object.

stop( )
Simulates a click on the browser's Stop button.

Internet Explorer Methods

navigate( )
Loads and displays the specified URL.

Event Handlers

onblur
Invoked when the window loses focus.

onerror
Invoked when a JavaScript error occurs.

onfocus
Invoked when the window gains focus.

onload
Invoked when the document (or frameset) is fully loaded.

onmove
Invoked when the window is moved. Netscape 4 only.

onresize
Invoked when the window is resized.

onunload
Invoked when the browser leaves the current document or frameset.

Description

The Window object represents a browser window or frame. It is documented in detail in Chapter 13. In client-side JavaScript, the Window serves as the "global object," and all expressions are evaluated in the context of the current Window object. This means that no special syntax is required to refer to the current window, and you can use the properties of that window object as if they were global variables. For example, you can write document rather than window.document. Similarly, you can use the methods of the current window object as if they were functions: e.g., alert( ) instead of window.alert( ).

The Window object does have window and self properties that refer to the window object itself. You can use these to make the current window reference explicit rather than implicit. In addition to these two properties, the parent and top properties and the frames[] array refer to other Window objects related to the current one.

To refer to a frame within a window, use:

frames[i] or self.frames[i]  // Frames of current window
window.frames[i]             // Frames of specified window

To refer to the parent window (or frame) of a frame, use:

parent or self.parent  // Parent of current window
window.parent          // Parent of specified window

To refer to the top-level browser window from any frame contained within it, use:

top or self.top  // Top window of current frame
window.top       // Top window of specified frame

New top-level browser windows are created with the Window.open( ) method. When you call this method, save the return value of the open( ) call in a variable and use that variable to reference the new window. In JavaScript 1.1, the opener property of the new window is a reference to the window that opened it.

In general, the methods of the Window object manipulate the browser window or frame in some way. The alert( ), confirm( ), and prompt( ) methods are notable: they interact with the user through simple dialog boxes.

See Chapter 13 for an in-depth overview of the Window object, and see the individual reference pages for complete details on all the Window properties, methods, and event handlers.

See Also

Document; Chapter 13; AbstractView in the DOM reference section

Window.alert( )display a message in a dialog box

Availability

JavaScript 1.0

Synopsis

window.alert(message)

Arguments

message
The plain-text (not HTML) string to display in a dialog box popped up over window.

Description

The alert( ) method displays the specified message to the user in a dialog box. The dialog box contains an OK button that the user can click to dismiss the dialog box.

On Windows platforms, the dialog box displayed by alert( ) is modal, and JavaScript execution pauses until the user dismisses it. In Netscape 4 on Unix platforms, however, the alert( ) dialog box is nonmodal, and execution continues uninterrupted.

Usage

Perhaps the most common use of the alert( ) method is to display error messages when the user's input to some form element is invalid in some way. The alert dialog box can inform the user of the problem and explain what needs to be corrected to avoid the problem in the future.

The appearance of the alert( ) dialog box is platform-dependent, but it generally contains graphics that indicate an error, warning, or alert message of some kind. While alert( ) can display any desired message, the alert graphics of the dialog box mean that this method is not appropriate for simple informational messages like "Welcome to my home page" or "You are the 177th visitor this week!"

Note that the message displayed in the dialog box is a string of plain text, not formatted HTML. You can use the newline character "\n" in your strings to break your message across multiple lines. You can also do some rudimentary formatting using spaces and can approximate horizontal rules with underscore characters, but the results depend greatly on the font used in the dialog box, and thus are system-dependent.

See Also

Window.confirm( ), Window.prompt( )

Window.back( )go back to previous document

Availability

Netscape 4

Synopsis

window.back( ) 

Description

Calling back( ) makes the browser display the document previously displayed in window, exactly as if the user had clicked on the window's Back button.

Note that for framed documents, there may be differences between the behavior of Window.back( ) and History.back( ).

Window.blur( )remove keyboard focus from a top-level window

Availability

JavaScript 1.1

Synopsis

window.blur( ) 

Description

The blur( ) method removes keyboard focus from the top-level browser window specified by the Window object. If the Window object is a frame, keyboard focus is given to the top-level window that contains that frame. On most platforms, a top-level window is sent to the background (i.e., to the bottom of the window stack) when keyboard focus is taken from it.

See Also

Window.focus( )

Window.captureEvents( )specify event types to be captured Netscape 4

Availability

Synopsis

window.captureEvents(eventmask) 
document.captureEvents(eventmask) 
layer.captureEvents(eventmask)

Arguments

eventmask
An integer that specifies the type of events that the window, document, or layer should capture. This value should be one of the static event type constants defined by the Event class, or it should be a group of event type constants combined with the bitwise-OR (|) or addition operators.

Description

captureEvents( ) is a method of the Window, Document, and Layer classes. Its purpose is the same for all three: in the Netscape 4 event model, captureEvents( ) specifies that all events of a given type or types occurring within the specified window, document, or layer should be passed to the window, document, or layer instead of to the object on which they actually occurred.

The type of the events to be captured is specified by eventmask, a bitmask comprised of static constants defined by the Event class. See the "Event.TYPE" reference page for a full list of these bitmask constants.

See Also

Event, Window.handleEvent( ), Window.releaseEvents( ), Window.routeEvent( ); Chapter 19; EventTarget.addEventListener( ) in the DOM reference section

Window.clearInterval( )stop periodically executing code

Availability

JavaScript 1.2

Synopsis

window.clearInterval(intervalId)

Arguments

intervalId
The value returned by the corresponding call to setInterval( ).

Description

clearInterval( ) stops the repeated execution of code that was started by a call to setInterval( ). intervalId must be the value that was returned by a call to setInterval( ).

See Also

Window.setInterval( )

Window.clearTimeout( )cancel deferred execution

Availability

JavaScript 1.0

Synopsis

window.clearTimeout(timeoutId)

Arguments

timeoutId
A value returned by setTimeout( ) that identifies the timeout to be canceled.

Description

clearTimeout( ) cancels the execution of code that has been deferred with the setTimeout( ) method. The timeoutId argument is a value returned by the call to setTimeout( ) and identifies which (of possibly more than one) block of deferred code to cancel.

See Also

Window.setTimeout( )

Window.close( )close a browser window

Availability

JavaScript 1.0

Synopsis

window.close( ) 

Description

The close( ) method closes the top-level browser window specified by window. A window can close itself by calling self.close( ) or simply close( ).

In JavaScript 1.1, only windows opened by JavaScript can be closed by JavaScript. This prevents malicious scripts from causing the user's browser to exit.

There is no meaningful way to close a frame within a window. Thus, the close( ) method should be invoked only for Window objects that represent top-level browser windows, not for those that represent frames.

See Also

Window.open( ), the closed and opener properties of Window

Window.confirm( )ask a yes-or-no question

Availability

JavaScript 1.0

Synopsis

window.confirm(question)

Arguments

question
The plain text (not HTML) string to be displayed in the dialog box. It should generally express a question you want the user to answer.

Returns

true if the user clicks the OK button; false if the user clicks the Cancel button.

Description

The confirm( ) method displays the specified question in a dialog box that pops up over window. The appearance of the dialog box is platform-dependent, but it generally contains graphics that indicate that the user is being asked a question. The dialog box contains OK and Cancel buttons that the user can use to answer the question. If the user clicks the OK button, confirm( ) returns true. If the user clicks Cancel, confirm( ) returns false.

The dialog box that is displayed by the confirm( ) method is modal -- that is, it blocks all user input to the main browser window until the user dismisses the dialog box by clicking on the OK or Cancel buttons. Since this method returns a value depending on the user's response to the dialog box, JavaScript execution pauses in the call to confirm( ), and subsequent statements are not executed until the user responds to the dialog box.

Usage

Note that the question displayed in the dialog box is a string of plain text, not formatted HTML. You can use the newline character, "\n", in your strings to break your question across multiple lines. You can also do some rudimentary formatting using spaces and can approximate horizontal rules with underscore characters, but the results depend greatly on the font used in the dialog box and thus are system-dependent.

Also, there is no way to change the labels that appear in the buttons of the dialog box (to make them read Yes and No, for example). Therefore, you should take care to phrase your question or message in such a way that OK and Cancel are suitable responses.

See Also

Window.alert( ), Window.prompt( )

Window.defaultStatusthe default status line text

Availability

JavaScript 1.0

Synopsis

window.defaultStatus 

Description

defaultStatus is a read/write string property that specifies the default text that will appear in the window's status line. Web browsers typically use the status line to display the browser's progress while loading a file and to display the destination of hypertext links that the mouse is over. While it is not displaying any of these transient messages, the status line is, by default, blank. However, you can set the defaultStatus property to specify a default message to be displayed when the status line is not otherwise in use, and you can read the defaultStatus property to determine what the default message is. The text you specify may be temporarily overwritten with other messages, such as those that are displayed when the user moves the mouse over a hypertext link, but the defaultStatus message is always redisplayed when the transient message is erased.

If you set defaultStatus for a Window object that is a frame, the message you specify is visible whenever the mouse is within that frame (regardless of whether that frame has focus). When you specify defaultStatus for a top-level window that contains no frames, your message is always visible when the window is visible. If you specify defaultStatus for a top-level window that contains frames, your message is visible only when the mouse is over the borders that separate the frames. Thus, in order to guarantee visibility of a message in a framed document, you should set defaultStatus for all frames in the document.

Usage

defaultStatus is used to display semipermanent messages in the status line. To display transient messages, use the status property.

See Also

Window.status

Window.focus( )give keyboard focus to a top-level window

Availability

JavaScript 1.1

Synopsis

window.focus( ) 

Description

The focus( ) method gives keyboard focus to the top-level browser window specified by the Window object. If the Window object is a frame, keyboard focus is given to the frame and to the top-level window that contains that frame.

On most platforms, a top-level window is brought forward to the top of the window stack when it is given focus.

See Also

Window.blur( )

Window.forward( )go forward to next document

Availability

Netscape 4

Synopsis

window.forward( ) 

Description

Calling forward( ) makes the browser display the next document in window, exactly as if the user had clicked on the window's Forward button.

Note that for framed documents, there may be differences between the behavior of Window.forward( ) and History.forward( ).

Window.handleEvent( )pass an event to the appropriate handler

Availability

Netscape 4

Synopsis

window.handleEvent(event) 
document.handleEvent(event)
layer.handleEvent(event) 
htmlElement.handleEvent(event)

Arguments

event
An Event object to be handled.

Returns

Whatever value is returned by the event handler that is invoked to handle event.

Description

handleEvent( ) is a method of the Window, Document, and Layer classes and of all HTML elements that support event handlers. When invoked on any object o, handleEvent( ) determines the type of its event argument and passes that Event object to the appropriate handler of o.

See Also

Window.routeEvent( ); Chapter 19

Window.home( )display the home page

Availability

Netscape 4

Synopsis

window.home( ) 

Description

Calling home( ) makes the browser display its own configured home page, as if the user had clicked the browser's Home button.

Window.moveBy( )move a window to a relative position

Availability

JavaScript 1.2

Synopsis

window.moveBy(dx, dy)

Arguments

dx
The number of pixels to move the window to the right.

dy
The number of pixels to move the window down.

Description

moveBy( ) moves the window to the relative position specified by dx and dy. For security reasons, browsers may restrict scripts so they cannot move a window off the screen.

Window.moveTo( )move a window to an absolute position

Availability

JavaScript 1.2

Synopsis

window.moveTo(x, y)

Arguments

x
The X-coordinate of the new window position.

y
The Y-coordinate of the new window position.

Description

moveTo( ) moves the window so its upper-left corner is at the position specified by x and y. For security resasons, browsers may restrict this method so it cannot move a window offscreen.

Window.namethe name of a window

Availability

JavaScript 1.0; read/write in JavaScript 1.1

Synopsis

window.name 

Description

The name property is a string that specifies the name of window. This property is read-only in JavaScript 1.0 and read/write in JavaScript 1.1. The name of a top-level window is initially specified by the name argument of the Window.open( ) method. The name of a frame is initially specified by the name attribute of the <frame> HTML tag.

The name of a top-level window or frame may be used as the value of a target attribute of an <a> or <form> tag. Using the target attribute in this way specifies that the hyperlinked document or the results of form submission should be displayed in the named window.

The initial window opened by the browser and any windows opened with the New Web Browser menu item initially have no name (i.e., name == ""), so these windows cannot be addressed with a target attribute from a separate top-level window. In JavaScript 1.1, you can set the name attribute to remedy this situation.

See Also

Form.target, Link.target

Window.navigate( )load a new URL

Availability

Internet Explorer 3

Synopsis

window.navigate(url)

Arguments

url
A string that specifies the URL to be loaded and displayed.

Description

The Window.navigate( ) method of Internet Explorer loads the specified url into the specified window ("navigates to" the url).

navigate( ) is not supported by Netscape. The same function can be accomplished both in Netscape and IE by assigning the desired url to the location property of the desired window.

See Also

Location, the location property of the Window object

Window.onblurthe handler invoked when the window loses keyboard focus

Availability

JavaScript 1.1

Synopsis

<body onblur="handler" ... >
<frameset onblur="handler" ... >
window.onblur

Description

The onblur property of a Window specifies an event handler function that is invoked when the window loses keyboard focus.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onblur attribute of the <body> or <frameset> tags.

In the Netscape 4 event model, the onblur handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

Usage

If your web page has animation, you can use the onblur( ) event handler to stop the animation when the window doesn't have the input focus. In theory, if the window doesn't have the focus, the user probably can't see it or isn't paying attention to it.

See Also

Window.blur( ), Window.focus( ), Window.onfocus; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Window.onerrorthe handler invoked when a JavaScript error occurs

Availability

JavaScript 1.1; buggy in Netscape 6/6.1

Synopsis

You register an onerror event handler like this:

window.onerror=handler-func

The browser invokes the handler like this:

window.onerror(message, url, line)

Arguments

message
A string that specifies the error message for the error that occurred.

url
A string that specifies the URL of the document in which the error occurred.

line
A number that specifies the line number at which the error occurred.

Returns

true if the handler has handled the error and JavaScript should take no further action; false if JavaScript should post the default error message dialog box for this error.

Description

The onerror property of the Window object specifies an error handler function that is invoked when a JavaScript error occurs in code executing in that window. By default, JavaScript displays an error dialog box when an error occurs. You can customize error handling by providing your own onerror event handler.

You define an onerror event handler for a window by setting the onerror property of a Window object to an appropriate function. Note that unlike other event handlers in JavaScript, the onerror handler cannot be defined in an HTML tag.

When the onerror handler is invoked, it is passed three arguments: a string specifying the error message, a string specifying the URL of the document in which the error occurred, and a number that specifies the line number at which the error occurred. An error handling function may do anything it wants with these arguments: it may display its own error dialog box or log the error in some way, for example. When the error handling function is done, it should return true if it has completely handled the error and wants JavaScript to take no further action or false if it has merely noted or logged the error in some fashion and still wants JavaScript to display the error message in its default dialog box.

Note that while this event handler returns true to tell the browser to take no further action, most Form and form element event handlers return false to prevent the browser from performing some action, such as submitting a form. This inconsistency can be confusing.

You can turn off error handling entirely for a window by setting the onerror property of the window to a function that returns true and does nothing else. You can restore the default error-handling behavior (the dialog box) by setting onerror to a function that returns false and does nothing else.

Bugs

This event handler is correctly triggered by errors in Netscape 6 and Netscape 6.1, but the values passed as the message, URL, and line number arguments are incorrect, so although you can use it to detect the occurrence of an error, you cannot use it to obtain any useful information about the error.

Window.onfocusthe handler invoked when a window is given focus

Availability

JavaScript 1.1

Synopsis

<body onfocus="handler" ... >
<frameset onfocus="handler" ... >
window.onfocus

Description

The onfocus property of a Window specifies an event handler function that is invoked when the window is given keyboard focus.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onfocus attribute of the <body> or <frameset> tags.

In the Netscape 4 event model, the onfocus handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

Usage

If your web page has animation, you can use the onfocus event handler to start the animation and the onblur handler to stop it, so it runs only when the user is paying attention to the window.

See Also

Window.blur( ), Window.focus( ), Window.onblur; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Window.onloadthe handler invoked when a document finishes loading

Availability

JavaScript 1.0

Synopsis

<body onload="handler" ... > <frameset onload="handler" ... > window.onload

Description

The onload property of a Window specifies an event handler function that is invoked when a document or frameset is completely loaded into its window or frame.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onload attribute of the <body> or <frameset> tags.

When the onload event handler is invoked, you can be certain that the document has fully loaded, and therefore that all scripts within the document have executed, all functions within scripts are defined, and all forms and other document elements have been parsed and are available through the Document object.

Usage

If any of your document's event handlers depend on the document being fully loaded, you should check that it is loaded before executing those handlers. If the network connection were to stall out after a button appeared in the document but before the parts of the document that the button relied on were loaded, the user would get unintended behavior or an error message after clicking the button. One good way to verify that the document is loaded is to use the onload handler to set a variable -- loaded, for example -- to true and to check the value of this variable before doing anything that depends on the complete document being loaded.

See Also

Window.onunload; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Window.onmovethe handler invoked when a window is moved

Availability

Netscape 4; not supported on Netscape 4 Unix platforms

Synopsis

<body onmove="handler" ... >
<frameset onmove="handler" ... >
window.onmove

Description

The onmove property of the Window object specifies an event handler function that is invoked when the user moves a top-level window to a new position on the screen.

The initial value of this property is a function that contains the JavaScript statements specified by the onmove attribute of the HTML <body> or <frameset> tag that defined the window. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

The onmove handler function is passed an Event object as an argument. The properties of this object contain information about the new position of the window.

Window.onresizethe handler invoked when a window is resized

Availability

JavaScript 1.2

Synopsis

<body onresize="handler" ... >
<frameset onresize="handler" ... >
window.onresize

Description

The onresize property of the Window object specifies an event handler function that is invoked when the user changes the size of the window or frame.

The initial value of this property is a function that contains the JavaScript statements specified by the onresize attribute of the HTML <body> or <frameset> tag that defined the window. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onresize handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

In Netscape, the new size of the window is available from the width and height properties of the Event object.

Window.onunloadthe handler invoked when the browser leaves a page

Availability

JavaScript 1.0

Synopsis

<body onunload="handler" ... >
<frameset onunload="handler" ... >
window.onunload

Description

The onunload property of a Window specifies an event handler function that is invoked when the browser "unloads" a document or frameset in preparation for loading a new one.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onunload attribute of the <body> or <frameset> tags. The onunload event handler provides the opportunity to perform any necessary cleanup of the browser state before a new document is loaded.

When the browser leaves a site using frames, the onunload handler of the frameset is invoked before the onunload handler for each of the frames. This is the reverse of the order in which the onload event handler is invoked.

The onunload( ) handler is invoked when the user has instructed the browser to leave the current page and move somewhere else. Therefore, it is usually inappropriate to delay the loading of the desired new page by popping up dialog boxes (with Window.confirm( ) or Window.prompt( ), for example) from an onunload event handler.

See Also

Window.onload; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Window.open( )open a new browser window or locate a named window

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

window.open(url, name, features, replace)

Arguments

url
An optional string that specifies the URL to be displayed in the new window. If this argument is omitted, or if the empty string is specified, the new window does not display a document.

name
An optional string of alphanumeric and underscore characters that specifies a name for the new window. This name can be used as the value of the target attribute of <a> and <form> HTML tags. If this argument names a window that already exists, the open( ) method does not create a new window, but simply returns a reference to the named window. In this case, the features argument is ignored.

features
A string that specifies which features of a standard browser window are to appear in the new window. The format of this string is specified in the "Window Features" section. This argument is optional; if it is not specified, the new window has all the standard features.

replace
An optional boolean argument that specifies whether the URL loaded into the new page should create a new entry in the window's browsing history or replace the current entry in the browsing history. If this argument is true, no new history entry is created. This argument was added in JavaScript 1.1. Note that it doesn't make much sense to use this argument for newly created windows; it is intended for use when changing the contents of an existing window.

Returns

A reference to a Window object, which may be a newly created or an already existing one, depending on the name argument.

Description

The open( ) method looks up an existing window or opens a new browser window. If the name argument specifies the name of an existing window, a reference to that window is returned. The returned window displays the URL specified by url, but the features argument is ignored. This is the only way in JavaScript to obtain a reference to a window which is known only by name.

If the name argument is not specified, or if no window with that name already exists, the open( ) method creates a new browser window. The created window displays the URL specified by url and has the name specified by name and the size and controls specified by features (the format of this argument is described in the next section). If url is the empty string, open( ) opens a blank window.

The name argument specifies a name for the new window. This name may contain only alphanumeric characters and the underscore character. It may be used as the value of the target attribute of an <a> or <form> tag in HTML to force documents to be displayed in the window.

In JavaScript 1.1, when you use Window.open( ) to load a new document into a named window, you can pass the replace argument to specify whether the new document has its own entry in the window's browsing history or whether it replaces the history entry of the current document. If replace is true, the new document replaces the old. If this argument is false or is not specified, the new document has its own entry in the Window's browsing history. This argument provides functionality much like that of the Location.replace( ) method.

Don't confuse Window.open( ) with Document.open( ) -- the two methods perform very different functions. For clarity in your code, you may want to use Window.open( ) instead of open( ). In event handlers defined as HTML attributes, open( ) is usually interpreted as Document.open( ), so in this case, you must use Window.open( ).

Window Features

The features argument is a comma-separated list of features that will appear in the window. If this optional argument is empty or not specified, all features are present in the window. On the other hand, if features specifies any one feature, any features that do not appear in the list do not appear in the window. The string should not contain any spaces or other whitespace. Each element in the list has the format:

feature[=value] 

For most features, the value is yes or no. For these features, the equals sign and the value may be omitted -- if the feature appears, yes is assumed, and if it doesn't, no is assumed. For the width and height features, value is required and must specify a size in pixels.

The available features and their meanings are:

channelmode
Specifies whether the window should appear in channel mode. IE 4 only.

dependent
If set to "no", specifies that the new window should not be a dependent child of the current window. Netscape 4 only.

directories
Directory buttons, such as "What's New" and "What's Cool". Netscape only.

fullscreen
Specifies whether the window should appear in full-screen mode. IE 4 only.

height
Specifies the height, in pixels, of the window's document display area.

innerHeight
Specifies the height, in pixels, of the window's document display area. Netscape 4 only.

innerWidth
Specifies the width, in pixels, of the window's document display area. Netscape 4 only.

left
The X-coordinate, in pixels, of the window. IE 4 only. In Netscape, use screenX.

location
The input field for entering URLs directly into the browser.

menubar
The menu bar.

outerHeight
Specifies the total height, in pixels, of the window. Netscape 4 only.

innerWidth
Specifies the total width, in pixels, of the window. Netscape 4 only.

resizable
If this feature is not present or is set to no, the window does not have resize handles around its border. (Depending on the platform, the user may still have ways to resize the window.) Note that a common bug is to misspell this feature as "resizeable," with an extra "e."

screenX
The X-coordinate, in pixels, of the window. Netscape 4 only. Use left in IE 4.

screenY
The Y-coordinate, in pixels, of the window. Netscape 4 only. Use top in IE 4.

scrollbars
Enables horizontal and vertical scrollbars when they are necessary.

status
The status line.

toolbar
The browser toolbar, with Back and Forward buttons, etc.

top
The Y-coordinate, in pixels, of the window. IE 4 only. Use screenY in Netscape.

width
Specifies the width, in pixels, of the window's document display area.

See Also

Location.replace( ), Window.close( ), the closed and opener properties of Window

Window.print( )print the document

Availability

Netscape 4, Internet Explorer 5

Synopsis

window.print( ) 

Description

Calling print( ) prints the current document, exactly as if the user had clicked the browser's Print button.

Window.prompt( )get string input in a dialog box

Availability

JavaScript 1.0

Synopsis

window.prompt(message, default)

Arguments

message
The plain-text (not HTML) string to be displayed in the dialog box. It should ask the user to enter the information you want.

default
A string that is displayed as the default input in the dialog box. Pass the empty string ("") to make prompt( ) display an empty input box.

Returns

The string entered by the user, the empty string if the user did not enter a string, or null if the user clicked Cancel.

Description

The prompt( ) method displays the specified message in a dialog box that also contains a text input field and OK, Clear, and Cancel buttons. Platform-dependent graphics in the dialog box help indicate to the user that her input is desired.

If the user clicks the Cancel button, prompt( ) returns null. If the user clicks the Clear button, prompt( ) erases any current text in the input field. If the user clicks the OK button, prompt( ) returns the value currently displayed in the input field.

The dialog box that is displayed by the prompt( ) method is modal -- that is, it blocks all user input to the main browser window until the user dismisses the dialog box by clicking on the OK or Cancel buttons. Since this method returns a value depending on the user's response to the dialog box, JavaScript execution pauses in the call to prompt( ), and subsequent statements are not executed until the user responds to the dialog box.

See Also

Window.alert( ), Window.confirm( )

Window.releaseEvents( )stop capturing events

Availability

Netscape 4

Synopsis

window.releaseEvents(eventmask) 
document.releaseEvents(eventmask) 
layer.releaseEvents(eventmask)

Arguments

eventmask
An integer that specifies the type of events that the window, document, or layer should stop capturing. This value should be one of the static event type constants defined by the Event class, or it should be a group of event type constants combined with the bitwise-OR (|) or addition operator.

Description

The releaseEvents( ) method of the Window, Document, and Layer objects performs the opposite action of the captureEvents( ) method of those classes. In the Netscape 4 event model, releaseEvents( ) specifies that the window, document, or layer should no longer capture events of the types specified by eventmask. See the "Event.TYPE" reference page for a list of the constants that can be used in the eventmask argument.

See Also

Event, Window.captureEvents( ), Window.handleEvent( ), Window.routeEvent( ); Chapter 19; EventTarget.removeEventListener( ) in the DOM reference section

Window.resizeBy( )resize a window by a relative amount

Availability

JavaScript 1.2

Synopsis

window.resizeBy(dw, dh)

Arguments

dw
The number of pixels by which to increase the width of the window.

dh
The number of pixels by which to increase the height of the window.

Description

resizeBy( ) resizes window by the relative amounts specified by dh and dw. For security reasons, the browser may restrict this method so it makes either the width or height of the window less than 100 pixels.

Window.resizeTo( )resize a window

Availability

JavaScript 1.2

Synopsis

window.resizeTo(width, height)

Arguments

width
The desired width for the window.

height
The desired height for the window.

Description

resizeTo( ) resizes window so it is width pixels wide and height pixels high. For security reasons, the browser may restrict this method so that neither width nor height is smaller than 100 pixels.

Window.routeEvent( )pass a captured event to the next handler

Availability

Netscape 4

Synopsis

window.routeEvent(event) 
document.routeEvent(event)
layer.routeEvent(event)

Arguments

event
The captured Event object to be routed to the next event handler.

Returns

Whatever value was returned by the handler to which the event was routed.

Description

routeEvent( ) is a method of the Window, Document, and Layer classes, and it behaves the same for all three. When a captured Event object, event, is passed to an event handler of window, document, or layer, that handler may choose to pass the event on to the next interested event handler, if any. If the window, document, or layer contains some other window (frame), document, or layer that has also used captureEvents( ) to register interest in events of that type, the event is routed to the appropriate handler on that window, document, or layer object.

On the other hand, if there is no containing window, document, or layer object that has expressed interest in the event, routeEvent( ) passes the event object to the appropriate event handler of the object on which the event originated. The combination of captureEvents( ) and routeEvent( ) forms the basis of the "trickle-down" event model of Netscape 4.

See Also

Window.captureEvents( ), Window.handleEvent( ), Window.releaseEvents( ); Chapter 19

Window.scroll( )scroll a document in a window

Availability

JavaScript 1.1; deprecated in JavaScript 1.2

Synopsis

window.scroll(x, y)

Arguments

x
The X-coordinate to scroll to.

y
The Y-coordinate to scroll to.

Description

The scroll( ) method moves the window's document within the window so the specified x- and y-coordinates of the document appear in the upper-left corner of the window.

The X-coordinate increases to the right, and the Y-coordinate increases down the page. Thus, scroll(0,0) always places the top-left corner of the document in the top-left corner of the window.

In JavaScript 1.2, the scrollTo( ) and scrollBy( ) methods are preferred over scroll( ).

Window.scrollBy( )scroll the document by a relative amount

Availability

JavaScript 1.2

Synopsis

window.scrollBy(dx, dy)

Arguments

dx
The number of pixels by which to scroll the document to the right.

dy
The number of pixels by which to scroll the document down.

Description

scrollBy( ) scrolls the document displayed in window by the relative amounts specified by dx and dy.

Window.scrollTo( )scroll the document

Availability

JavaScript 1.2

Synopsis

window.scrollTo(x, y)

Arguments

x
The document X-coordinate that is to appear at the left edge of the window's document display area.

y
The document Y-coordinate that is to appear at the top of the window's document display area.

Description

scrollTo( ) scrolls the document displayed within window so the point in the document specified by the x- and y-coordinates is displayed in the upper-left corner, if possible.

scrollTo( ) is preferred over the JavaScript 1.1 Window.scroll( ) method, which does the same thing but has an inadequately descriptive name.

Window.setInterval( )periodically execute specified code

Availability

JavaScript 1.2; IE 4 supports only one of the two forms

Synopsis

window.setInterval(code, interval)
window.setInterval(func, interval,args...)

Arguments

code
A string of JavaScript code to be periodically executed. If this string contains multiple statements, they must be separated from each other by semicolons.

func
A JavaScript function to be periodically executed. This form of the method is not available in IE 4.

interval
An integer that specifies the interval, in milliseconds, between invocations of code or func.

args...
Any number of arbitrary values to be passed as arguments to each invocation of func.

Returns

A value that can be passed to Window.clearInterval( ) to cancel the periodic execution of code or func.

Description

setInterval( ) repeatedly executes the JavaScript statements specified in the string code, at intervals of interval milliseconds.

In Netscape 4, but not IE 4, a function may be passed as the first argument instead of a string. In this form of setInterval( ), the specified function, func, is repeatedly invoked, at intervals of interval milliseconds. Any additional argument values, args, passed to setInterval( ) are passed as arguments to each invocation of func( ).

In both forms, the setInterval( ) method returns a value that can later be passed to Window.clearInterval( ) to stop code or func from being repeatedly executed.

setInterval( ) is related to setTimeout( ). Use setTimeout( ) when you want to defer the execution of code but do not want it to be repeatedly executed.

See Also

Window.clearInterval( ), Window.setTimeout( )

Window.setTimeout( )defer execution of code

Availability

JavaScript 1.0

Synopsis

window.setTimeout(code, delay)

Arguments

code
A string that contains the JavaScript code to be executed after the delay has elapsed.

delay
The amount of time, in milliseconds, before the JavaScript statements in the string code should be executed.

Returns

An opaque value ("timeout id") that can be passed to the clearTimeout( ) method to cancel the execution of code.

Description

The setTimeout( ) method defers the execution of the JavaScript statements in the string code for delay milliseconds. Once the specified number of milliseconds has elapsed, the statements in code are executed normally. Note that they are executed only once. To execute code repeatedly, code must itself contain a call to setTimeout( ) to register itself to be executed again. In JavaScript 1.2, you can use Window.setInterval( ) to register code that is executed at periodic intervals.

The statements in the string code are executed in the context of window; i.e., window is the current window for those statements. If more than one statement appears in code, the statements must be separated by semicolons.

See Also

Window.clearTimeout( ), Window.setInterval( )

Window.statusspecify a transient status-line message

Availability

JavaScript 1.0

Synopsis

window.status 

Description

status is a read/write string property that specifies a transient message to appear in the window's status line. The message generally appears only for a limited amount of time -- until it is overwritten by another message or until the user moves the mouse to some other area of the window, for example. When a message specified with status is erased, the status line returns to its default blank state or to the default message specified by the defaultStatus property.

Although only top-level windows have status lines, you can also set the status property of frames. Doing so displays the specified message in the top-level window's status line. Transient messages set by frames are visible regardless of which frame currently has focus or which frame the mouse is currently in. This behavior differs from that of the defaultStatus property.

Usage

status is used to display transient messages in the status line. To display semipermanent messages, use the defaultStatus property.

In general, setting the status property is useful only from event handlers and in code fragments deferred with the Window.setTimeout( ) method. If you set status directly from a script, the message is not visible to the user. It is not displayed right away, and when it is displayed, it is likely to be immediately overwritten by a browser message such as "Document: done".

If you want to set the status property in the onmouseover event handler of a hypertext link, you must return true from that event handler because when the mouse goes over a link, the default action is to display the URL of that link, thereby overwriting any status message set by the event handler. By returning true from the event handler, you cancel this default action and leave your own status message displayed (until the mouse moves off the link).

See Also

Window.defaultStatus

Window.stop( )stop loading the document

Availability

Netscape 4

Synopsis

window.stop( )

Description

Calling stop( ) stops the browser from loading the current document, exactly as if the user had clicked the browser's Stop button.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.