home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


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

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

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

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.captureEvents( )see Window.captureEvents( )

Document.handleEvent( )see Window.handleEvent( )

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

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

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

  • When the defaultStatus property is set for a frame, the specified status message is visible only when the mouse is within that frame.

  • The top and parent properties of a top-level browser window always refer to the top-level window itself. These properties are really useful only for frames.

  • The close( ) method is not useful for Window objects that are frames.

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

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.handleEvent( )see Window.handleEvent( )

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

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.

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

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

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.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.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.releaseEvents( )see Window.releaseEvents( )

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

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

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

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

  • If you set options.length to 0, all options in the Select object are cleared.

  • If you set options.length to a value less than the current value, the number of options in the Select object is decreased, and those at the end of the array disappear.

  • If you set an element in the options[] array to null, that option is removed from the Select object, and the elements above it in the array are moved down, changing their indices to occupy the new space in the array.

  • If you create a new Option object with the Option( ) constructor (see the "Option" reference entry), you can add that option to the end of list of options in the Select object by assigning the newly created option to a position at the end of the options[] array. To do this, set options[options.length].

See Also

Option

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

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

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



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.