[Previous reference file]
Math
Object. A built-in object that has properties and methods
for mathematical constants and functions. For example, the Math object's
PI property has the value of pi.
Syntax
To use a Math object:
1. Math.propertyName
2. Math.methodName(parameters)
Parameters
propertyName is one of the properties listed
below.
methodName is one of the methods listed below.
Property of
None. The Math object is a top-level, built-in
JavaScript object.
Implemented in
Navigator 2.0
Description
You reference the constant PI as Math.PI
.
Constants are defined with the full precision of real numbers in JavaScript.
Similarly, you reference Math functions as methods. For example, the
sine function is Math.sin(argument)
, where argument is
the argument.
It is often convenient to use the with statement
when a section of code uses several Math constants and methods, so
you don't have to type "Math" repeatedly. For example,
with (Math) {
a = PI * r*r
y = r*sin(theta)
x = r*cos(theta)
}
Properties
The Math object has the following properties:
Methods
The Math object has the following methods:
Event handlers
None.
Examples
See the examples for the individual properties and
methods.
max
Method. Returns the greater of two numbers.
Syntax
Math.max(number1, number2)
Parameters
number1 and number2 are any numeric arguments
or the properties of existing objects.
Method of
Math
Implemented in
Navigator 2.0
Examples
The following function evaluates the variables x and
y:
function getMax(x,y) {
return Math.max(x,y)
}
If you pass getMax the values 10 and 20, it returns
20; if you pass it the values -10 and -20, it returns -10.
See also
min method
MAX_VALUE
Property. The maximum numeric value representable in
JavaScript.
Syntax
Number.MAX_VALUE
Property of
Number
Implemented in
Navigator 3.0
Tainted?
No
Description
The maximum numeric value representable in JavaScript
The MAX_VALUE property has a value of approximately
1.79E+308. Values larger than MAX_VALUE are represented as
"Infinity".
Because MAX_VALUE is a constant, it is a read-only
property of Number.
Examples
The following code multiplies two numeric values. If the
result is less than or equal to MAX_VALUE, the func1 function
is called; otherwise, the func2 function is called.
if (num1 * num2 <= Number.MAX_VALUE)
func1()
else
func2()
See also
MIN_VALUE,
NaN,
NEGATIVE_INFINITY,
POSITIVE_INFINITY properties
method
Property. A string specifying how form field input information
is sent to the server.
Syntax
formName.method
Parameters
formName is either the name of a form or an element
in the forms array.
Property of
Form object
Implemented in
Navigator 2.0
Tainted?
No
Description
The method property is a reflection of the METHOD
attribute of the <FORM> tag. The method property should evaluate
to either "get" or "post."
You can set the method property at any time.
Examples
The following function returns the value of the
musicForm method property:
function getMethod() {
return document.musicForm.method
}
See also
action,
encoding,
target properties;
Form object
MimeType
Object. A MIME type (Multipart Internet Mail Extension)
supported by the client.
Syntax
To use a MimeType object:
navigator.mimeTypes[index].propertyName
Parameters
index is either an integer representing a MIME type
supported by the client or a string containing the type of a MimeType
object (from the type property).
propertyName is one of the properties listed
below.
Property of
The mimeTypes array is a property of
navigator.
The MimeType object is a member of the
mimeTypes array; each Plugin object also has an array of
MimeType objects.
Implemented in
Navigator 3.0
Description
Each MimeType object is an element in the
mimeTypes array.
For example, the following table summarizes the values
for displaying JPEG images:
The mimeTypes array
The mimeTypes array contains an entry for each MIME
type supported by the client (either internally, via helper applications,
or by plug-ins). For example, if a client supports three MIME types, these
MIME types are reflected as navigator.mimeTypes[0]
,
navigator.mimeTypes[1]
, and
navigator.mimeTypes[2]
.
Each element of the mimeTypes array is a
MimeType object.
To use the mimeTypes array:
1. navigator.mimeTypes[index]
2. navigator.mimeTypes.length
index is either an integer representing a MIME type
supported by the client or a string containing the type of a MimeType
object (from the type property).
To obtain the number of MIME types supported by the client,
use the length property:
navigator.mimeTypes.length
.
Elements in the mimeTypes array are read-only. For
example, the statement navigator.mimeTypes[0]="video/quicktime"
has no effect.
The mimeTypes array used with the Plugin object
Each Plugin object has its own mimeTypes
array, which contains an entry for each MIME type handled by the plug-in.
For information, see
Plugin.
Properties
The MimeType object has the following properties:
The mimeTypes array has the following properties:
Methods
Event handlers
None.
Examples
The following code displays the type, description,
suffixes, and enabledPlugin properties for each MimeType
object on a client:
document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>",
"<TH ALIGN=left>i",
"<TH ALIGN=left>type",
"<TH ALIGN=left>description",
"<TH ALIGN=left>suffixes",
"<TH ALIGN=left>enabledPlugin.name</TR>")
for (i=0; i < navigator.mimeTypes.length; i++) {
document.writeln("<TR VALIGN=TOP><TD>",i,
"<TD>",navigator.mimeTypes[i].type,
"<TD>",navigator.mimeTypes[i].description,
"<TD>",navigator.mimeTypes[i].suffixes)
if (navigator.mimeTypes[i].enabledPlugin==null) {
document.writeln(
"<TD>None",
"</TR>")
} else {
document.writeln(
"<TD>",navigator.mimeTypes[i].enabledPlugin.name,
"</TR>")
}
}
document.writeln("</TABLE>")
The preceding example displays output similar to the
following:
See also
Plugin object
mimeTypes
Property. An array of all MIME types supported by the client.
See the MimeType object for
information.
Tainted?
No
min
Method. Returns the lesser of two numbers.
Syntax
Math.min(number1, number2)
Parameters
number1 and number2 are any numeric arguments
or the properties of existing objects.
Method of
Math
Implemented in
Navigator 2.0
Examples
The following function evaluates the variables x and
y:
function getMin(x,y) {
return Math.min(x,y)
}
If you pass getMin the values 10 and 20, it returns
10; if you pass it the values -10 and -20, it returns -20.
See also
max method
MIN_VALUE
Property. The smallest positive numeric value representable
in JavaScript.
Syntax
Number.MIN_VALUE
Property of
Number
Implemented in
Navigator 3.0
Tainted?
No
Description
The MIN_VALUE property is the number closest to
zero, not the most negative number, that JavaScript can represent.
MIN_VALUE has a value of approximately 2.22E-308.
Values smaller than MIN_VALUE ("underflow values") are converted to
zero.
Because MIN_VALUE is a constant, it is a read-only
property of Number.
Examples
The following code divides two numeric values. If the result
is greater than or equal to MIN_VALUE, the func1 function is
called; otherwise, the func2 function is called.
if (num1 / num2 >= Number.MIN_VALUE)
func1()
else
func2()
See also
MAX_VALUE,
NaN,
NEGATIVE_INFINITY,
POSITIVE_INFINITY properties
Implemented in
Navigator 2.0
name
Property. A string specifying the name of an object.
Syntax
1. objectName.name
2. frameReference.name
3. frameReference.frames.name
4. radioName[index].name
5. imageName.name
6. navigator.plugins[index].name
7. windowReference.name
8. windowReference.frames.name
Parameters
objectName is either the value of the NAME attribute
of any of the objects listed below or an element in the elements
array.
frameReference is a valid way of referring to a
frame, as described in the Frame object.
radioName is the value of the NAME attribute of
a Radio object.
selectName is either the value of the NAME attribute
of a Select object or an element in the elements array.
imageName is either the value of the NAME attribute
of a Image object or an element in the images array.
index is either an integer representing a plug-in
installed on the client or a string containing the name of a Plugin
object (from the name property).
windowReference is a valid way of referring to a
window, as described in the window object.
Property of
Button object,
Checkbox object,
FileUpload object,
Form object,
Frame object,
Hidden object,
Image object,
Password object,
Plugin object,
Radio object, Reset
object, Select object,
Submit object, Text
object, Textarea object,
window object
Implemented in
Navigator 2.0
Navigator 3.0: property of FileUpload, Form, Image, and Plugin
objects
Tainted?
Yes
Description
The value of the name property differs between the
window object and other objects. The name property is a read-only
property for the FileUpload object, Image object, and
Plugin object.
window object
The name property for the window object is
represented by form 7 and form 8 of the syntax. The name property
represents the value of the windowName argument described in the
window object syntax. Both forms of the syntax
represent the same value.
name is a read-only property.
Image and Plugin objects
The name property for Image and Plugin
objects is represented by forms 5-6 of the syntax.
-
-
For Image objects, the name property represents the value of
the NAME attribute. For images created with the Image() constructor, the
value of the name property is null.
-
For Plugin objects, the name property is the plug-in's name
and is supplied by the plug-in itself. Each plug-in should have a name that
uniquely identifies it.
name is a read-only property.
All other objects
The name property for all other objects is represented
by forms 1 through 4 of the syntax. For all objects except Image,
Plugin, and window, the name property initially reflects
the value of the NAME attribute. Changing the name property overrides
this setting.
You can set the name property at any time.
The name property is the same for every radio button
in a single Radio object. Individual radio buttons are referenced
by their position in the Radio array.
Do not confuse the name property with the label
displayed on a Button, Reset, or Submit object. The
value property specifies the label for these objects. The name
property is not displayed on-screen; it is used to reference the objects
programmatically.
For a Frame object, the values specified by forms
1, 2, and 3 of the syntax are the same.
If multiple objects on the same form have the same NAME
attribute, an array of the given name is created automatically. Each element
in the array represents an individual Form object. Elements are indexed
in source order starting at zero. For example, if two text elements and a
textarea element on the same form have their NAME attribute set to "myField,"
an array with the elements myField[0], myField[1], and myField[2] is
created.
Examples
In the following example, the valueGetter function
uses a for loop to iterate over the array of elements on the
valueTest form. The msgWindow window displays the names of
all the elements on the form:
newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}
In the following example, the first statement creates a
window called netscapeWin. The second statement displays the value
"netscapeHomePage" in the Alert dialog box, because "netscapeHomePage" is
the value of the windowName argument of netscapeWin.
netscapeWin=window.open("http://home.netscape.com","netscapeHomePage")
alert(netscapeWin.name)
For Plugin objects, see the examples for the
Plugin object.
See also
For button, reset, and submit:
value property
For Plugin:
description,
filename,
length properties
NaN
Property. A special value representing Not-A-Number. This
value is represented as the unquoted literal NaN.
Syntax
Number.NaN
Property of
Number
Implemented in
Navigator 3.0
Tainted?
No
Description
JavaScript prints the value Number.NaN
as
NaN
.
NaN always compares unequal to any other number,
including NaN itself; you cannot check for the not-a-number value by comparing
to Number.NaN. Use the
isNaN function insead.
You might use the NaN property to indicate an error
condition for a function that should return a valid number.
Because NaN is a constant, it is a read-only property
of Number.
Examples
In the following example, if month has a value greater
than 12, it is assigned NaN, and a message is displayed indicating valid
values.
var month = 13
if (month < 1 || month > 12) {
month = Number.NaN
alert("Month must be between 1 and 12.")
}
See also
MAX_VALUE,
MIN_VALUE,
NEGATIVE_INFINITY,
POSITIVE_INFINITY properties;
isNaN,
parseFloat,
parseInt functions
navigator
Object. Contains information about the version of Navigator
in use.
Syntax
To use a navigator object:
1. navigator.propertyName
2. navigator.methodName
Parameters
propertyName is one of the properties listed
below.
methodName is one of the methods listed below.
Property of
None
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: added mimeTypes, plugins properties; added
javaEnabled method
Description
Use the navigator object to determine which version
of the Navigator your users have, what MIME types the user's Navigator can
handle, and what plug-ins the user has installed.
Properties
The navigator object has the following properties:
Methods
The navigator object has the following methods:
Event handlers
None.
Examples
See the examples for the individual properties and
methods.
NEGATIVE_INFINITY
Property. A special numeric value representing negative
infinity. This value is represented as "-Infinity".
Syntax
Number.NEGATIVE_INFINITY
Property of
Number
Implemented in
Navigator 3.0
Tainted?
No
Description
This value behaves mathematically like an infinity; for
example, anything multiplied by infinity is infinity, and anything divided
by infinity is zero.
Because NEGATIVE_INFINITY is a constant, it is a
read-only property of Number.
Examples
In the following example, the variable smallNumber
is assigned a value that is smaller than the minimum value. When the
if statement executes, smallNumber has the value "-Infinity",
so the func1 function is called.
var smallNumber = -Number.MAX_VALUE*10
if (smallNumber == Number.NEGATIVE_INFINITY)
func1()
else
func2()
See also
MAX_VALUE,
MIN_VALUE,
NaN,
POSITIVE_INFINITY properties
next
Property. A string specifying the complete URL of the next
history entry.
Syntax
history.next
Property of
history object
Implemented in
Navigator 3.0
Tainted?
Yes
Description
The next property reflects the URL that would be
used if the user chose Forward from the Go menu. This property has a value
only if data tainting is enabled; if data tainting is not enabled,
next has no value.
next is a read-only property.
Examples
The following example determines whether
history.next contains the string "NETSCAPE.COM". If it does, the function
myFunction is called.
if (history.next.indexOf("NETSCAPE.COM") != -1) {
myFunction(history.next)
}
See also
current,
previous properties;
"Using data tainting for security"
Number
Object. Lets you work with numeric values. The
Number object is an object wrapper for primitive numeric values.
Syntax
To create a Number object:
numberObjectName = new Number()
To use a Number object:
numberObjectName.propertyName
Parameters
numberObjectName is either the name of a new object
or a property of an existing object. When using Number properties,
numberObjectName is either the name of an existing Number object
or a property of an existing object.
propertyName is one of the properties listed
below.
Property of
None
Implemented in
Navigator 3.0
Description
The Number object is a built-in JavaScript object.
The primary uses for the Number object are:
-
-
To access its constant properties, which represent the largest and smallest
representable numbers, positive and negative infinity, and the Not-a-Number
value.
-
To create numeric objects that you can add properties to. Most likely, you
will rarely need to create a Number object.
Properties
The Number object has the following properties:
Methods
Event handlers
None.
Examples
Example 1. The following example uses the
Number object's properties to assign values to several numeric
variables:
biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN
Note that these properties are properties of the Number()
constructor itself, not of individual Number objects.
Example 2. The following example creates a
Number object, myNum, then adds a description property
to all Number objects. Then a value is assigned to the myNum
object's description property.
myNum = new Number(65)
Number.prototype.description=null
myNum.description="wind speed"
onAbort
Event handler. An abort event occurs when the user aborts
the loading of an image (for example by clicking a link or clicking the Stop
button). The onAbort event handler executes JavaScript code when an abort
event occurs.
See the relevant objects for the onAbort syntax.
Event handler of
Image
Implemented in
Navigator 3.0
Examples
In the following example, an onAbort handler in an
Image object displays a message when the user aborts the image load:
<IMG NAME="aircraft" SRC="f15e.gif"
onAbort="alert('You didn\'t get to see the image!')">
See also
onError,
onLoad event handlers
onBlur
Event handler. A blur event occurs when a form element
loses focus or when a window or frame loses focus. The blur event can result
from a blur method or from the user clicking the mouse on another
object or window or tabbing with the keyboard. The onBlur event handler executes
JavaScript code when a blur event occurs.
For windows, frames, and framesets, the onBlur event handler
specifies JavaScript code to execute when a window loses focus.
A frame's onBlur event handler overrides an onBlur event
handler in the <BODY> tag of the document loaded into frame.
Note
On some platforms, placing an onBlur event handler in a <FRAMESET>
tag has no effect. Please see the release notes (after starting Netscape,
choose Release Notes from the Help menu).
See the relevant objects for the onBlur syntax.
Event handler of
Button object,
Checkbox object,
FileUpload object,
Frame object,
Password object,
Radio object, Reset
object, Select object,
Submit object, Text
object, Textarea object,
window object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame, Password,
Radio, Reset, Submit, and window
Examples
Example 1: Validate form input. In the following
example, userName is a required text field. When a user attempts to
leave the field, the onBlur event handler calls the required function
to confirm that userName has a legal value.
<INPUT TYPE="text" VALUE="" NAME="userName" onBlur="required(this.value)">
Example 2: Change the background color of a window.
In the following example, a window's onBlur and onFocus event handlers change
the window's background color depending on whether the window has focus.
<BODY BGCOLOR="lightgrey"
onBlur="document.bgColor='lightgrey'"
onFocus="document.bgColor='antiquewhite'">
Example 3: Change the background color of a frame.
The following example creates four frames. The source for each frame,
onblur2.html
has the <BODY> tag with the onBlur and onFocus
event handlers shown in Example 1. When the document loads, all frames are
"lightgrey". When the user clicks a frame, the onFocus event handler changes
the frame's background color to "antiquewhite". The frame that loses focus
is changed to "lightgrey". Note that the onBlur and onFocus event handlers
are within the <BODY> tag, not the <FRAME> tag.
<FRAMESET ROWS="50%,50%" COLS="40%,60%">
<FRAME SRC=onblur2.html NAME="frame1">
<FRAME SRC=onblur2.html NAME="frame2">
<FRAME SRC=onblur2.html NAME="frame3">
<FRAME SRC=onblur2.html NAME="frame4">
</FRAMESET>
The following code has the same effect as the previous
code, but is implemented differently. The onFocus and onBlur event handlers
are associated with the frame, not the document. The onBlur and onFocus event
handlers for the frame are specified by setting the onblur and
onfocus properties. For information on using new to specify
a string of JavaScript code to be compiled as a function, see the
Function object.
<SCRIPT>
function setUpHandlers() {
for (var i = 0; i < frames.length; i++) {
frames[i].onfocus=new Function("document.bgColor='antiquewhite'")
frames[i].onblur=new Function("document.bgColor='lightgrey'")
}
}
</SCRIPT>
<FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad=setUpHandlers()>
<FRAME SRC=onblur2.html NAME="frame1">
<FRAME SRC=onblur2.html NAME="frame2">
<FRAME SRC=onblur2.html NAME="frame3">
<FRAME SRC=onblur2.html NAME="frame4">
</FRAMESET>
Example 4: Close a window. In the following example,
a window's onBlur event handler closes the window when the window loses
focus.
<BODY onBlur="window.close()">
This is some text
</BODY>
See also
onChange,
onFocus event handlers
onChange
Event handler. A change event occurs when a select, text,
or textarea field loses focus and its value has been modified. The onChange
event handler executes JavaScript code when a change event occurs.
Use the onChange event handler to validate data after it
is modified by a user.
See the relevant objects for the onChange syntax.
Event handler of
FileUpload object,
Select object, Text
object, Textarea object
Implemented in
Examples
In the following example, userName is a text field.
When a user changes the text and leaves the field, the onChange event handler
calls the checkValue function to confirm that userName has
a legal value.
<INPUT TYPE="text" VALUE="" NAME="userName" onChange="checkValue(this.value)">
See also
onBlur,
onFocus event handlers
onClick
Event handler. A click event occurs when an object on a
form is clicked. The onClick event handler executes JavaScript code when
a click event occurs.
For checkboxes, links, radio buttons, reset buttons, and
submit buttons, the onClick event handler can return false to cancel the
action normally associated with a click event.
For example, the following code creates a hyperlink that,
when clicked, displays a confirm dialog box. If the user clicks the hyperlink
and then chooses cancel, the page specified by the hyperlink is not loaded.
<A HREF = "http://home.netscape.com/"
onClick="return confirm('Load Netscape home page?')">Netscape</A>
Returning false in an onClick event handler for a button
has no effect.
Note
On some platforms, returning false in an onClick event handler for a reset
button has no effect. Please see the release notes (after starting Netscape,
choose Release Notes from the Help menu).
See the relevant objects for the onClick syntax.
Event handler of
Button object,
Checkbox object,
Link object,
Radio object, Reset
object, Submit object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: added the ability to return false to cancel the action associated
with a click event
Examples
Example 1: Call a function when a user clicks a
button. Suppose you have created a JavaScript function called
compute. You can execute the compute function when the user
clicks a button by calling the function in the onClick event handler, as
follows:
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
In the preceding example, the keyword this refers
to the current object; in this case, the Calculate button. The construct
this.form refers to the form containing the button.
For another example, suppose you have created a JavaScript
function called pickRandomURL that lets you select a URL at random.
You can use the onClick event handler of a link to specify a value for the
HREF attribute of the <A> tag dynamically, as shown in the following
example:
<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="window.status='Pick a random URL'; return true">
Go!</A>
In the above example, the onMouseOver event handler specifies
a custom message for the Navigator status bar when the user places the mouse
pointer over the Go! anchor. As this example shows, you must return true
to set the window.status property in the onMouseOver event handler.
Example 2: Cancel the checking of a checkbox. The
following example creates a checkbox with an onClick event handler. The event
handler displays a confirm that warns the user that checking the checkbox
purges all files. If the user chooses Cancel, the onClick event handler returns
false and the checkbox is not checked.
<INPUT TYPE="checkbox" NAME="check1" VALUE="check1"
onClick="return confirm('This purges all your files. Are you sure?')"> Remove files
onError
Event handler. An error event occurs when the loading of
a document or image causes an error. The onError event handler executes
JavaScript code when an error event occurs.
An error event occurs only when a JavaScript syntax or
runtime error occurs, not when a Navigator error occurs. For example, if
you try set window.location.href='notThere.html'
and
notThere.html
does not exist, the resulting error message is
a Navigator error message; therefore, an onError event handler would not
intercept that message. However, an error event is triggered by a
bad URL within an <IMG> tag or by corrupted image data.
window.onerror
applies only to errors that
occur in the window containing window.onerror
, not in other
windows.
The onError event handler can be any of the following:
-
-
null to suppress all JavaScript error dialogs. Setting
window.onerror
to null means your users won't see JavaScript
errors caused by your own code.
-
The name of a function that handles errors (arguments are message text, URL,
and line number of the offending line). To suppress the standard JavaScript
error dialog, the function must return true. See Example 3 below.
-
A variable or property that contains null or a valid function reference.
If you write an error-handling function, you have three
options for reporting errors:
-
-
Trace errors but let the standard JavaScript dialog report them (use an error
handling function that returns false or does not return a value)
-
Report errors yourself and disable the standard error dialog (use an error
handling function that returns true)
-
Turn off all error reporting (set the onError event handler to null)
See the relevant objects for the onError syntax.
Event handler of
Image object,
window object
Implemented in
Navigator 3.0
Examples
Example 1: Null event handler. In the following
<IMG> tag, the code onError="null"
suppresses error messages
if errors occur when the image loads.
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"
onError="null">
Example 2: Null event handler for a window. The
onError event handler for windows cannot be expressed in HTML. Therefore,
you must spell it all lowercase and set it in a <SCRIPT> tag. The following
code assigns null to the onError handler for the entire window, not just
the Image object. This suppresses all JavaScript error messages, including
those for the Image object.
<SCRIPT>
window.onerror=null
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2">
However, if the Image object has a custom onError
event handler, the handler would execute if the image had an error. This
is because window.onerror=null
suppresses JavaScript error messages,
not onError event handlers.
<SCRIPT>
window.onerror=null
function myErrorFunc() {
alert("The image had a nasty error.")
}
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"
onError="myErrorFunc()">
In the following example, window.onerror=null
suppresses all error reporting. Without onerror=null
, the code
would cause a stack overflow error because of infinite recursion.
<SCRIPT>
window.onerror = null;
function testErrorFunction() {
testErrorFunction();
}
</SCRIPT>
<BODY onload="testErrorFunction()">
test message
</BODY>
Example 3: Error handling function. The following
example defines a function, myOnError, that intercepts JavaScript
errors. The function uses three arrays to store the message, URL, and line
number for each error. When the user clicks the Display Error Report button,
the displayErrors function opens a window and creates an error report
in that window. Note that the function returns true to suppress the standard
JavaScript error dialog.
<SCRIPT>
window.onerror = myOnError
msgArray = new Array()
urlArray = new Array()
lnoArray = new Array()
function myOnError(msg, url, lno) {
msgArray[msgArray.length] = msg
urlArray[urlArray.length] = url
lnoArray[lnoArray.length] = lno
return true
}
function displayErrors() {
win2=window.open('','window2','scrollbars=yes')
win2.document.writeln('<B>Error Report</B><P>')
for (var i=0; i < msgArray.length; i++) {
win2.document.writeln('<B>Error in file:</B> ' + urlArray[i] + '<BR>')
win2.document.writeln('<B>Line number:</B> ' + lnoArray[i] + '<BR>')
win2.document.writeln('<B>Message:</B> ' + msgArray[i] + '<P>')
}
win2.document.close()
}
</SCRIPT>
<BODY onload="noSuchFunction()">
<FORM>
<BR><INPUT TYPE="button" VALUE="This button has a syntax error"
onClick="alert('unterminated string)">
<P><INPUT TYPE="button" VALUE="Display Error Report"
onClick="displayErrors()">
</FORM>
This example produces the following output:
Error Report
Error in file: file:///c%7C/temp/onerror.html
Line number: 34
Message: unterminated string literal
Error in file: file:///c%7C/temp/onerror.html
Line number: 34
Message: missing ) after argument list
Error in file: file:///c%7C/temp/onerror.html
Line number: 30
Message: noSuchFunction is not defined
Example 4: Event handler calls a function. In the
following <IMG> tag, the onError event handler calls the function
badImage if errors occur when the image loads.
<SCRIPT>
function badImage(theImage) {
alert('Error: ' + theImage.name + ' did not load properly.')
}
</SCRIPT>
<FORM>
<IMG NAME="imageBad2" SRC="orca.gif" ALIGN="left" BORDER="2"
onError="badImage(this)">
</FORM>
See also
onAbort,
onLoad event handlers
onFocus
Event handler. A focus event occurs when a window, frame,
or frameset receives focus or when a form element receives input focus. The
focus event can result from a focus method or from the user clicking
the mouse on an object or window or tabbing with the keyboard. Selecting
within a field results in a select event, not a focus event. The onFocus
event handler executes JavaScript code when a focus event occurs.
A frame's onFocus event handler overrides an onFocus event
handler in the <BODY> tag of the document loaded into frame.
Note that placing an alert in an onFocus event handler
results in recurrent alerts: when you press OK to dismiss the alert, the
underlying window gains focus again and produces another focus event.
Note
On some platforms, placing an onFocus event handler in a <FRAMESET>
tag has no effect. Please see the release notes (after starting Netscape,
choose Release Notes from the Help menu).
See the relevant objects for the onFocus syntax.
Event handler of
Button object,
Checkbox object,
FileUpload object,
Frame object,
Password object,
Radio object, Reset
object, Select object,
Submit object, Text
object, Textarea object,
window object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame, Password,
Radio, Reset, Submit, and window
Examples
The following example uses an onFocus handler in the
valueField Textarea object to call the valueCheck
function.
<INPUT TYPE="textarea" VALUE="" NAME="valueField" onFocus="valueCheck()">
See also the examples for the
onBlur event handler.
See also
onBlur,
onChange event handlers
onLoad
Event handler. A load event occurs when Navigator finishes
loading a window or all frames within a <FRAMESET> tag. The onLoad
event handler executes JavaScript code when a load event occurs.
Use the onLoad event handler within either the BODY or
the <FRAMESET> tag, for example, <BODY
onLoad="...">
.
In a FRAMESET and FRAME relationship, an onLoad event within
a frame (placed in the <BODY> tag) occurs before an onLoad event within
the FRAMESET (placed in the <FRAMESET> tag).
For images, the onLoad event handler indicates the script
to execute when an image is displayed. Do not confuse displaying an image
with loading an image. You can load several images, then display them one
by one in the same Image object by setting the object's src
property. If you change the image displayed in this way, the onLoad event
handler executes every time an image is displayed, not just when the image
is loaded into memory.
If you specify an onLoad event handler for an Image
object that displays a looping GIF animation (multi-image GIF), each loop
of the animation triggers the onLoad event, and the event handler executes
once for each loop.
You can use the onLoad event handler to create a JavaScript
animation by repeatedly setting the src property of an Image
object. See the Image object for
information.
Event handler of
Image object,
window object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: event handler of Image
Examples
Example 1: Display message when page loads. In the
following example, the onLoad event handler displays a greeting message after
a Web page is loaded.
<BODY onLoad="window.alert("Welcome to the Brave New World home page!")>
Example 2: Display alert when image loads. The following
example creates two Image objects, one with the Image() constructor
and one with the <IMG> tag. Each Image object has an onLoad
event handler that calls the displayAlert function, which displays
an alert. For the image created with the <IMG> tag, the alert displays
the image name. For the image created with the Image() constructor, the alert
displays a message without the image name. This is because the onLoad handler
for an object created with the Image() constructor must be the name of a
function, and it cannot specify parameters for the displayAlert
function.
<SCRIPT>
imageA = new Image(50,50)
imageA.onload=displayAlert
imageA.src="cyanball.gif"
function displayAlert(theImage) {
if (theImage==null) {
alert('An image loaded')
}
else alert(theImage.name + ' has been loaded.')
}
</SCRIPT>
<IMG NAME="imageB" SRC="greenball.gif" ALIGN="top"
onLoad=displayAlert(this)><BR>
Example 3: Looping GIF animation. The following
example displays an image, birdie.gif
, that is a looping GIF
animation. The onLoad event handler for the image increments the variable
cycles, which keeps track of the number of times the animation has
looped. To see the value of cycles, the user clicks the button labeled
Count Loops.
<SCRIPT>
var cycles=0
</SCRIPT>
<IMG ALIGN="top" SRC="birdie.gif" BORDER=0
onLoad="++cycles">
<INPUT TYPE="button" VALUE="Count Loops"
onClick="alert('The animation has looped ' + cycles + ' times.')">
Example 4: Change GIF animation displayed. The following
example uses an onLoad event handler to rotate the display of six GIF animations.
Each animation is displayed in sequence in one Image object. When
the document loads, !anim0.html
is displayed. When that animation
completes, the onLoad event handler causes the next file,
!anim1.html
, to load in place of the first file. After the last
animation, !anim5.html
, completes, the first file is again
displayed. Notice that the changeAnimation function does not call
itself after changing the src property of the Image object.
This is because when the src property changes, the image's onLoad
event handler is triggered and the changeAnimation function is
called.
<SCRIPT>
var whichImage=0
var maxImages=5
function changeAnimation(theImage) {
++whichImage
if (whichImage <= maxImages) {
var imageName="!anim" + whichImage + ".gif"
theImage.src=imageName
} else {
whichImage=-1
return
}
}
</SCRIPT>
<IMG NAME="changingAnimation" SRC="!anim0.gif" BORDER=0 ALIGN="top"
onLoad="changeAnimation(this)">
See also the examples for the
Image object.
See also
onAbort,
onError,
onUnload event handlers
onMouseOut
Event handler. A mouseOut event occurs each time the mouse
pointer leaves an area (client-side image map) or link from inside that area
or link. The onMouseOut event handler executes JavaScript code when a mouseOut
event occurs.
If the mouse moves from one area into another in a client-side
image map, you'll get onMouseOut for the first area, then onMouseOver for
the second.
Area objects that use the onMouseOut event handler
must include the HREF attribute within the <AREA> tag.
You must return true within the event handler if you want
to set the status or defaultStatus properties with the onMouseOver
event handler.
See the relevant objects for the onMouseOut syntax.
Event handler of
Area object (see Link
object), Link object
Implemented in
Navigator 3.0
Examples
See the examples for the Link
object.
See also
onMouseOver event
handler
onMouseOver
Event handler. A mouseOver event occurs once each time
the mouse pointer moves over an object or area from outside that object or
area. The onMouseOver event handler executes JavaScript code when a mouseOver
event occurs.
If the mouse moves from one area into another in a client-side
image map, you'll get onMouseOut for the first area, then onMouseOver for
the second.
Area objects that use the onMouseOver event handler
must include the HREF attribute within the <AREA> tag.
You must return true within the event handler if you want
to set the status or defaultStatus properties with the onMouseOver
event handler.
See the relevant objects for the onMouseOver syntax.
Event handler of
Area object (see Link
object), Link object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: event handler of Area
Examples
By default, the HREF value of an anchor displays in the
status bar at the bottom of the Navigator when a user places the mouse pointer
over the anchor. In the following example, the onMouseOver event handler
provides the custom message "Click this if you dare."
<A HREF="http://home.netscape.com/"
onMouseOver="window.status='Click this if you dare!'; return true">
Click me</A>
See onClick for an example
of using onMouseOver when the <A> tag's HREF attribute is set
dynamically.
See also the examples for the
Link object.
See also
onMouseOut event handler
onReset
Event handler. A reset event occurs when a user resets
a form (clicks a Reset button). The onReset event handler executes JavaScript
code when a reset event occurs.
See the relevant objects for the onReset syntax.
Event handler of
Form object
Implemented in
Navigator 3.0
Examples
The following example displays a Text object with
the default value "CA" and a reset button. If the user types a state abbreviation
in the Text object and then clicks the reset button, the original
value of "CA" is restored. The form's onReset event handler displays a message
indicating that defaults have been restored.
<FORM NAME="form1" onReset="alert('Defaults have been restored.')">
State:
<INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"><P>
<INPUT TYPE="reset" VALUE="Clear Form" NAME="reset1">
</FORM>
See also
reset method,
Reset object
onSelect
Event handler. A select event occurs when a user selects
some of the text within a text or textarea field. The onSelect event handler
executes JavaScript code when a select event occurs.
See the relevant objects for the onSelect syntax.
Event handler of
Text object,
Textarea object
Implemented in
Navigator 2.0
Examples
The following example uses an onSelect handler in the
valueField Text object to call the selectState
function.
<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">
onSubmit
Event handler. A submit event occurs when a user submits
a form. The onSubmit event handler executes JavaScript code when a submit
event occurs.
You can use the onSubmit event handler to prevent a form
from being submitted; to do so, put a return statement that returns
false in the event handler. Any other returned value lets the form submit.
If you omit the return statement, the form is submitted.
See the relevant objects for the onSubmit syntax.
Event handler of
Form object
Implemented in
Navigator 2.0
Examples
In the following example, the onSubmit event handler calls
the validate function to evaluate the data being submitted. If the
data is valid, the form is submitted; otherwise, the form is not submitted.
<FORM onSubmit="return validate(this)">
...
</FORM>
See also the examples for the
Form object.
See also
Submit object,
submit method
onUnload
Event handler. An unload event occurs when you exit a document.
The onUnload event handler executes JavaScript code when an unload event
occurs.
Use the onUnload event handler within either the BODY or
the <FRAMESET> tag, for example, <BODY
onUnload="...">
.
In a frameset and frame relationship, an onUnload event
within a frame (placed in the <BODY> tag) occurs before an onUnload
event within the frameset (placed in the <FRAMESET> tag).
Event handler of
window object
Implemented in
Navigator 2.0
Examples
In the following example, the onUnload event handler calls
the cleanUp function to perform some shutdown processing when the
user exits a Web page:
<BODY onUnload="cleanUp()">
See also
onLoad event handler
open (document object)
Method. Opens a stream to collect the output of
write or writeln methods.
Syntax
document.open(["mimeType"])
[windowReference.]document.open("text/html","replace")
Parameters
mimeType is an optional argument that specifies
the type of document to which you are writing. If you do not specify a
mimeType, text/html
is the default.
-
-
text/html
specifies a document containing ASCII text with HTML
formatting.
-
text/plain
specifies a document containing plain ASCII text
with end-of-line characters to delimit displayed lines.
-
image/gif
specifies a document with encoded bytes constituting
a GIF header and pixel data.
-
image/jpeg
specifies a document with encoded bytes constituting
a JPEG header and pixel data.
-
image/x-bitmap
specifies a document with encoded bytes constituting
a bitmap header and pixel data.
-
plugIn loads the specified plug-in and uses it as the destination
for write and writeln methods. For example, "x-world/vrml"
loads the VR Scout VRML plug-in from Chaco Communications, and
"application/x-director" loads the Macromedia Shockwave plug-in. Plug-in
MIME types are only valid if the user has installed the required plug-in
software.
windowReference is a valid way of referring to a
window, as described in the window
object.
"replace" causes the new document to reuse the history
entry that the previous document used. When you specify "replace" while opening
a document, the target window's history length is not incremented even after
you write and close.
Method of
document
Implemented in
Description
The open method opens a stream to collect the output
of write or writeln methods. If the mimeType is text
or image, the stream is opened to layout; otherwise, the stream is opened
to a plug-in. If a document exists in the target window, the open
method clears it.
End the stream by using the document.close()
method. The close method causes text or images that were sent to layout
to display. After using document.close()
, issue
document.open()
again when you want to begin another output
stream.
In Navigator 3.0, document.open() or document.open("text/html")
clears the current document if it has finished loading. This is because this
type of open call writes a default <BASE HREF=> tag so you can
generate relative URLs based on the generating script's document base.
Using "replace"
The "replace" keyword causes the new document to
reuse the history entry that the previous document used. When you specify
"replace" while opening a document, the target window's history length is
not incremented even after you write and close.
"replace" is typically used on a window that has a blank
document or an "about:blank" URL. After "replace" is specified, the
write method typically generates HTML for the window, replacing the
history entry for the blank URL. Take care when using generated HTML on a
window with a blank URL. If you do not specify "replace", the generated HTML
has its own history entry, and the user can press the Back button and back
up until the frame is empty.
After document.open("text/html","replace")
executes, history.current for the target window is the URL of document
that executed document.open.
Examples
Example 1. The following function calls
document.open to open a stream before issuing a write method:
function windowWriter1() {
var myString = "Hello, world!"
msgWindow.document.open()
msgWindow.document.write("<P>" + myString)
msgWindow.document.close()
}
Example 2. The following function calls
document.open with the "replace" keyword to open a stream before issuing
write methods. The HTML code in the write methods is written
to msgWindow, replacing the current history entry. The history length
of msgWindow is not incremented.
function windowWriter2() {
var myString = "Hello, world!"
msgWindow.document.open("text/html","replace")
msgWindow.document.write("<P>" + myString)
msgWindow.document.write("<P>history.length is " +
msgWindow.history.length)
msgWindow.document.close()
}
The following code creates the msgWindow window
and calls the function:
msgWindow=window.open('','',
'toolbar=yes,scrollbars=yes,width=400,height=300')
windowWriter2()
Example 3. In the following example, the
probePlugIn function determines whether a user has the Shockwave plug-in
installed:
function probePlugIn(mimeType) {
var havePlugIn = false
var tiny = window.open("", "teensy", "width=1,height=1")
if (tiny != null) {
if (tiny.document.open(mimeType) != null)
havePlugIn = true
tiny.close()
}
return havePlugIn
}
var haveShockwavePlugIn = probePlugIn("application/x-director")
See also
close (document object),
reload,
replace,
write,
writeln methods
open (window object)
Method. Opens a new web browser window. IE 3 has a
few bugs dealing with windows. When you open a window using the open()
method, the first parameter (for the url of the new window's document) will
be ignored. Because of this, you must assign the location afterwards. Another
bug deals with the opener property. When you open a new window, the
new window is given a property, opener, which points to the window
that opened it. There is no opener propery in IE 3.0. Both of these
problems are fixed in IE 3.01.
Syntax
[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])
Parameters
windowVar is the name of a new window. Use this
variable when referring to a window's properties, methods, and
containership.
URL specifies the URL to open in the new window.
See the location object for a description
of the URL components.
windowName is the window name to use in the TARGET
attribute of a FORM or <A> tag. windowName can contain only
alphanumeric or underscore (_) characters.
windowFeatures is a comma-separated list of any
of the following options and values:
toolbar[=yes|no]|[=1|0]
location[=yes|no]|[=1|0]
directories[=yes|no]|[=1|0]
status[=yes|no]|[=1|0]
menubar[=yes|no]|[=1|0]
scrollbars[=yes|no]|[=1|0]
resizable[=yes|no]|[=1|0]
width=pixels
height=pixels
You may use any subset of these options. Separate options
with a comma. Do not put spaces between the options. The
windowFeatures are:
-
-
toolbar creates the standard Navigator toolbar, with buttons such
as Back and Forward, if true.
-
location creates a Location entry field, if true.
-
directories creates the standard Navigator directory buttons, such
as What's New and What's Cool, if true.
-
status creates the status bar at the bottom of the window, if true.
-
menubar creates the menu at the top of the window, if true.
-
scrollbars creates horizontal and vertical scrollbars when the document
grows larger than the window dimensions, if true.
-
resizable allows a user to resize the window, if true.
-
width specifies the width of the window in pixels.
-
height specifies the height of the window in pixels.
Method of
window object
Implemented in
Navigator 2.0
Description
The open method opens a new Web browser window on
the client, similar to choosing New Web Browser from the File menu of the
Navigator. The URL argument specifies the URL contained by the new
window. If URL is an empty string, a new, empty window is created.
In event handlers, you must specify
window.open()
instead of simply using open()
. Due
to the scoping of static objects in JavaScript, a call to open()
without specifying an object name is equivalent to
document.open()
.
windowFeatures is an optional, comma-separated list
of options for the new window. The Boolean windowFeatures options
are set to true if they are specified without values, or as yes
or 1
. For example, open("", "messageWindow",
"toolbar")
and open("", "messageWindow", "toolbar=1")
both set the toolbar option to true. If windowName does not specify
an existing window and you do not specify windowFeatures, all Boolean
windowFeatures are true by default. If you specify any item in
windowFeatures, all other Boolean windowFeatures are false
unless you explicitly specify them. After a window is open, you cannot use
JavaScript to change the windowFeatures.
You can use open on an existing window, and if you
pass the empty string for the URL, you will get a reference to the existing
window, but not load anything into it. You can, for example, then look for
properties in the window.
Examples
In the following example, the windowOpener function
opens a window and uses write methods to display a message:
function windowOpener() {
msgWindow=window.open("","displayWindow","menubar=yes")
msgWindow.document.write
("<HEAD><TITLE>Message window</TITLE></HEAD>")
msgWindow.document.write
("<CENTER><BIG><B>Hello, world!</B></BIG></CENTER>")
}
The following is an onClick event handler that opens a
new client window displaying the content specified in the file
sesame.html
. The window opens with the specified option settings;
all other options are false because they are not specified.
<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
onClick="window.open ('sesame.html', 'newWin',
'scrollbars=yes,status=yes,width=300,height=300')">
</FORM>
Notice the use of single quotes (') inside the onClick
event handler.
See also
close (window object)
method
opener
Property. Specifies the window of the calling document
when a window is opened using the open method.
Syntax
window.opener
Property of
window object
Implemented in
Navigator 3.0
Tainted?
No
Description
When a source document opens a destination window by calling
the open method, the opener property specifies the window of
the source document. Evaluate the opener property from the destination
window.
This property persists across document unload in the opened
window.
You can change the opener property at any time.
Examples
Example 1: Close the opener. The following code
closes the window that opened the current window. When the opener window
closes, opener is unchanged. However, window.opener.name
then evaluates to undefined.
window.opener.close()
Example 2: Evaluate the name of the opener. A window
can determine the name of its opener as follows:
document.write("<BR>opener property is " + window.opener.name)
Example 3: Change the value of opener. The following
code changes the value of the opener property to null. After this
code executes, you cannot close the opener window as shown in Example 1.
window.opener=null
Example 4: Change a property of the opener. The
following code changes the background color of the window specified by the
opener property.
window.opener.document.bgColor='bisque'
See also
close (window object),
open (window object) methods
Option
Object. A Select object option created using the
Option() constructor. For information, see the
Select object.
options
Property. An array corresponding to options in a
Select object (OPTION tags) in source order. See the
Select object.
parent
Property. The parent property is a synonym for a
window or frame whose frameset contains the current frame.
Syntax
1. parent.propertyName
2. parent.methodName
3. parent.frameName
4. parent.frames[index]
Parameters
propertyName is the defaultStatus,
status, length, name, or parent property when
the calling parent refers to a window object.
propertyName is the length, name,
or parent property when the calling parent refers to a Frame
object.
methodName is any method associated with the
window object.
frameName and frames[index] are ways to refer
to frames.
Property of
Frame object,
window object
Implemented in
Navigator 2.0
Tainted?
No
Description
The parent property refers to the FRAMESET window
of a frame. Child frames within a frameset refer to sibling frames by using
"parent" in place of the window name as follows:
parent.frameName
or parent.frames[index]
. For example,
if the fourth frame in a set has NAME="homeFrame," sibling frames can refer
to that frame using parent.homeFrame
or
parent.frames[3]
.
You can use parent.parent
to refer to the
"grandparent" frame or window when a <FRAMESET> tag is nested within
a child frame.
The parent property is read-only. The value of the
parent property is
<object nameAttribute>
where nameAttribute is the NAME attribute if the
parent is a frame, or an internal reference if the parent is a window.
Examples
See the examples for the
Frame object.
parse
Method. Returns the number of milliseconds in a date string
since January 1, 1970, 00:00:00, local time.
Syntax
Date.parse(dateString)
Parameters
dateString is a string representing a date or a
property of an existing object.
Method of
Date
Implemented in
Navigator 2.0
Description
The parse method takes a date string (such as "Dec
25, 1995") and returns the number of milliseconds since January 1, 1970,
00:00:00 (local time). This function is useful for setting date values based
on string values, for example in conjunction with the setTime method
and the Date object.
Given a string representing a time, parse returns
the time value. It accepts the IETF standard date syntax: "Mon, 25 Dec 1995
13:30:00 GMT." It understands the continental US time-zone abbreviations,
but for general use, use a time-zone offset, for example, "Mon, 25 Dec 1995
13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich meridian).
If you do not specify a time zone, the local time zone is assumed. GMT and
UTC are considered equivalent.
Because the parse function is a static method of
Date, you always use it as Date.parse()
, rather than
as a method of a Date object you created.
Examples
If IPOdate is an existing Date object, then
IPOdate.setTime(Date.parse("Aug 9, 1995"))
See also
UTC method
parseFloat
Function. Parses a string argument and returns a floating
point number.
Syntax
parseFloat(string)
Parameters
string is a string that represents the value you
want to parse.
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: returns "NaN" on all platforms if the first character of the
string specified in parseFloat(string) cannot be converted to a number.
In previous releases, it returned "NaN" on Solaris and Irix and zero on all
other platforms.
Description
The parseFloat function is a built-in JavaScript
function. It is not a method associated with any object, but is part of the
language itself.
parseFloat parses its argument, a string, and returns
a floating point number. If it encounters a character other than a sign (
+ or -), numeral (0-9), a decimal point, or an exponent, then it returns
the value up to that point and ignores that character and all succeeding
characters.
If the first character cannot be converted to a number,
parseFloat returns "NaN".
For arithmetic purposes, the "NaN" value is not a number
in any radix. You can call the isNaN function to determine if the
result of parseFloat is "NaN." If "NaN" is passed on to arithmetic
operations, the operation results will also be "NaN."
Examples
The following examples all return 3.14:
parseFloat("3.14")
parseFloat("314e-2")
parseFloat("0.0314E+2")
var x = "3.14"
parseFloat(x)
The following example returns "NaN":
parseFloat("FF2")
See also
isNaN,
parseInt functions
parseInt
Function. Parses a string argument and returns an integer
of the specified radix or base.
Syntax
parseInt(string [,radix])
Parameters
string is a string that represents the value you
want to parse.
radix is an integer that represents the radix of
the return value.
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: returns "NaN" on all platforms if the first character of the
string specified in parseInt(string) cannot be converted to a number.
In previous releases, it returned "NaN" on Solaris and Irix and zero on all
other platforms.
Description
The parseInt function is a built-in JavaScript function.
It is not a method associated with any object, but is part of the language
itself.
The parseInt function parses its first argument,
a string, and attempts to return an integer of the specified radix (base).
For example, a radix of 10 indicates to convert to a decimal number, 8 octal,
16 hexadecimal, and so on. For radixes above 10, the letters of the alphabet
indicate numerals greater than 9. For example, for hexadecimal numbers (base
16), A through F are used.
If parseInt encounters a character that is not a
numeral in the specified radix, it ignores it and all succeeding characters
and returns the integer value parsed up to that point. parseInt truncates
numbers to integer values.
If the radix is not specified or is specified as zero,
JavaScript assumes the following:
-
-
If the input string begins with "0x," the radix is 16 (hexadecimal).
-
If the input string begins with "0," the radix is eight (octal).
-
If the input string begins with any other value, the radix is 10
(decimal).
If the first character cannot be converted to a number,
parseInt returns "NaN".
For arithmetic purposes, the "NaN" value is not a number
in any radix. You can call the isNaN function to determine if the
result of parseInt is "NaN." If "NaN" is passed on to arithmetic
operations, the operation results will also be "NaN."
Examples
The following examples all return 15:
parseInt("F", 16)
parseInt("17", 8)
parseInt("15", 10)
parseInt(15.99, 10)
parseInt("FXX123", 16)
parseInt("1111", 2)
parseInt("15*3", 10)
The following examples all return "NaN":
parseInt("Hello", 8)
parseInt("0x7", 10)
parseInt("FFF", 10)
Even though the radix is specified differently, the following
examples all return 17 because the input string begins with "0x."
parseInt("0x11", 16)
parseInt("0x11", 0)
parseInt("0x11")
See also
isNaN,
parseFloat functions;
valueOf method
Password
Object. A text field on an HTML form that conceals its
value by displaying asterisks (*). When the user enters text into the field,
asterisks (*) hide entries from view.
HTML syntax
To define a Password object, use standard HTML
syntax:
<INPUT
TYPE="password"
NAME="passwordName"
[VALUE="textValue"]
SIZE=integer
[onBlur="handlerText"]
[onFocus="handlerText"]>
HTML attributes
NAME="passwordName" specifies the name of the
Password object. You can access this value using the name property,
and you can use this name when indexing the elements array.
VALUE="textValue" specifies the initial value of
the Password object. You can access this value using the
defaultValue property.
SIZE=integer specifies the number of characters
the Password object can accommodate without scrolling.
Syntax
To use a Password object's properties and methods:
1. passwordName.propertyName
2. passwordName.methodName(parameters)
3. formName.elements[index].propertyName
4. formName.elements[index].methodName(parameters)
Parameters
passwordName is the value of the NAME attribute
of a Password object.
formName is either the value of the NAME attribute
of a Form object or an element in the forms array.
index is an integer representing a Password
object on a form or the name of a Password object as specified by
the NAME attribute.
propertyName is one of the properties listed
below.
methodName is one of the methods listed below.
Property of
Form object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: added type property; added onBlur and onFocus event
handlers
Description
A Password object on a form looks as follows:
A Password object is a form element and must be
defined within a <FORM> tag.
If a user interactively modifies the value in a password
field, you cannot evaluate it accurately unless data tainting is enabled.
See "Using data tainting for security"
and the value property.
Properties
The Password object has the following properties:
Methods
The Password object has the following methods:
Event handlers
Examples
The following example creates a Password object
with no default value:
<B>Password:</B> <INPUT TYPE="password" NAME="password" VALUE="" SIZE=25>
See also
Form object,
Text object
pathname
Property. A string specifying the url-path portion of the
URL.
Syntax
1. links[index].pathname
2. location.pathname
3. areaName.pathname
Parameters
index is an integer representing a Link object
or the name of a Link object as specified by the NAME attribute.
areaName is the value of the NAME attribute of an
Area object.
Property of
Area object (see Link
object), Link object,
location object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: property of Area
Tainted?
Yes
Description
The pathname property specifies a portion of the
URL. The pathname supplies the details of how the specified resource can
be accessed.
You can set the pathname property at any time, although
it is safer to set the href property to change a location. If the
pathname that you specify cannot be found in the current location, you will
get an error.
In event handlers, you must specify
window.location.pathname
instead of simply using
location.pathname
. Due to the scoping of static objects in
JavaScript, a call to location
without specifying an object
name is equivalent to document.location
, which is a synonym
for document.URL
.
See Section 3.1 of
RFC
1738 for complete information about the pathname.
Examples
See the examples for the
href property.
See also
hash,
host,
hostname,
href, port,
protocol,
search properties
PI
Property. The ratio of the circumference of a circle to
its diameter, approximately 3.14159.
Syntax
Math.PI
Property of
Math
Implemented in
Navigator 2.0
Tainted?
No
Description
Because PI is a constant, it is a read-only property
of Math.
Examples
The following function returns the value of pi:
function getPi() {
return Math.PI
}
See also
E,
LN2, LN10,
LOG2E, LOG10E,
SQRT1_2, SQRT2
properties
Plugin
Object. A plug-in module installed on the client.
Syntax
To use a Plugin object:
1. navigator.plugins[index].propertyName
2. navigator.plugins[pluginIndex][mimeTypeIndex].mimeTypePropertyName
Parameters
index is an integer representing a plug-in installed
on the client or a string containing the type of a Plugin object (from
the type property).
mimeTypeIndex is either an integer representing
a MIME type supported by the plug-in or a string containing the type of a
MimeType object (from the type property).
propertyName is one of the properties listed
below.
mimeTypePropertyName is a property of a
MimeType object. See
MimeType for a list of properties.
Property of
The plugins array is a property of
navigator.
The Plugin object is a member of the plugins
array.
Implemented in
Navigator 3.0
Description
A Plugin object is a plug-in installed on the client.
A plug-in is a software module that Navigator can invoke to display specialized
types of embedded data within the browser. The user can obtain a list of
installed plug-ins by choosing About Plug-ins from the Help menu.
Each Plugin object is an array containing one element
for each MIME type supported by the plug-in. Each element of the array is
a MimeType object. You can access the MimeType objects using
form 2 of the syntax. For example, the following code displays the
type and description properties of the first Plugin
object's first MimeType object.
myPlugin=navigator.plugins[0]
myMimeType=myPlugin[0]
document.writeln('myMimeType.type is ',myMimeType.type,"<BR>")
document.writeln('myMimeType.description is ',myMimeType.description)
The preceding code displays output similar to the
following:
myMimeType.type is video/quicktime
myMimeType.description is QuickTime for Windows
The Plugin object lets you dynamically determine
which plug-ins are installed on the client. You can write scripts to display
embedded plug-in data if the appropriate plug-in is installed, or display
some alternative information such as images or text if not.
Plug-ins can be platform dependent and configurable, so
a Plugin object's array of MimeType objects can vary from platform
to platform, and from user to user.
Each Plugin object is an element in the
plugins array.
When you use the <EMBED> tag to generate output from
a plug-in application, you are not creating a Plugin object. Use the
embeds array to reference plug-in instances created with
<EMBED> tags. See the embeds array.
The plugins array
You can reference the Plugin objects installed on
the client by using the plugins array. This array contains an entry
for each plug-in installed on the client in source order. Each element of
the plugins array is a Plugin object. For example, if three
plug-ins are installed on the client, these plug-ins are reflected as
navigator.plugins[0]
, navigator.plugins[1]
, and
navigator.plugins[2]
.
To use the plugins array:
1. navigator.plugins[index]
2. navigator.plugins.length
index is an integer representing a plug-in installed
on the client or a string containing the name of a Plugin object (from
the name property).
To obtain the number of plug-ins installed on the client,
use the length property: navigator.plugins.length
.
Elements in the plugins array are read-only. For
example, the statement navigator.plugins[0]="LiveAudio"
has
no effect.
Properties
The Plugin object has the following properties:
The plugins array has the following properties:
Methods
The Plugin object has the following methods:
The plugins array has the following methods:
Event handlers
None.
Examples
Example 1. The user can obtain a list of installed
plug-ins by choosing About Plug-ins from the Help menu. To see the code Navigator
uses for this report, choose About Plug-ins from the Help menu, then choose
Document Source from the View menu.
Example 2. The following code assigns shorthand
variables for the predefined LiveAudio properties.
var myPluginName = navigator.plugins["LiveAudio"].name
var myPluginFile = navigator.plugins["LiveAudio"].filename
var myPluginDesc = navigator.plugins["LiveAudio"].description
Example 3. The following code displays the message
"LiveAudio is configured for audio/wav" if the LiveAudio plug-in is installed
and is enabled for the "audio/wav" MIME type:
var myPlugin = navigator.plugins["LiveAudio"]
var myType = myPlugin["audio/wav"]
if (myType && myType.enabledPlugin == myPlugin)
document.writeln("LiveAudio is configured for audio/wav")
Example 4. The following expression represents the
number of MIME types that Shockwave can display:
navigator.plugins["Shockwave"].length
Example 5. The following code displays the name,
filename, description, and length properties for each
Plugin object on a client:
document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>",
"<TH ALIGN=left>i",
"<TH ALIGN=left>name",
"<TH ALIGN=left>filename",
"<TH ALIGN=left>description",
"<TH ALIGN=left># of types</TR>")
for (i=0; i < navigator.plugins.length; i++) {
document.writeln("<TR VALIGN=TOP><TD>",i,
"<TD>",navigator.plugins[i].name,
"<TD>",navigator.plugins[i].filename,
"<TD>",navigator.plugins[i].description,
"<TD>",navigator.plugins[i].length,
"</TR>")
}
document.writeln("</TABLE>")
The preceding example displays output similar to the
following:
See also
MimeType object;
embeds array
plugins
Property. An array of all plug-ins currently installed
on the client. See the Plugin object
for information.
Tainted?
No
port
Property. A string specifying the communications port that
the server uses for communications.
Syntax
1. links[index].port
2. location.port
3 areaName.port
Parameters
index is an integer representing a Link object
or the name of a Link object as specified by the NAME attribute.
areaName is the value of the NAME attribute of an
Area object.
Property of
Area object (see Link
object), Link object,
location object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: property of Area
Tainted?
Yes
Description
The port property specifies a portion of the URL.
The port property is a substring of the hostname property.
The hostname property is the concatenation of the host and
port properties, separated by a colon. When the port property
is 80 (the default), the host property is the same as the
hostname property.
You can set the port property at any time, although
it is safer to set the href property to change a location. If the
port that you specify cannot be found in the current location, you will get
an error. If the port property is not specified, it defaults to 80
on the server.
In event handlers, you must specify
window.location.port
instead of simply using
location.port
. Due to the scoping of static objects in JavaScript,
a call to location
without specifying an object name is equivalent
to document.location
, which is a synonym for
document.URL
.
See Section 3.1 of
RFC
1738 for complete information about the port.
Examples
See the examples for the
href property.
See also
hash,
host,
hostname,
href,
pathname,
protocol,
search properties
POSITIVE_INFINITY
Property. A special numeric value representing infinity.
This value is represented as "Infinity".
Syntax
Number.POSITIVE_INFINITY
Property of
Number
Implemented in
Navigator 3.0
Tainted?
No
Description
This value behaves mathematically like an infinity; for
example, anything multiplied by infinity is infinity, and anything divided
by infinity is zero.
JavaScript does not have a literal for Infinity.
Because POSITIVE_INFINITY is a constant, it is a
read-only property of Number.
Examples
In the following example, the variable bigNumber
is assigned a value that is larger than the maximum value. When the if
statement executes, bigNumber has the value "Infinity", so the
func1 function is called.
var bigNumber = Number.MAX_VALUE * 10
if (bigNumber == Number.POSITIVE_INFINITY)
func1()
else
func2()
See also
MAX_VALUE,
MIN_VALUE,
NaN,
NEGATIVE_INFINITY properties
pow
Method. Returns base to the exponent power,
that is, baseexponent.
Syntax
Math.pow(base, exponent)
Parameters
base is any numeric expression or a property of
an existing object.
exponent is any numeric expression or a property
of an existing object.
Method of
Math
Implemented in
Navigator 2.0
Examples
function raisePower(x,y) {
return Math.pow(x,y)
}
If x equals seven and y equals two,
raisePower returns 49 (seven to the power of two).
See also
exp,
log methods
previous
Property. A string specifying the complete URL of the previous
history entry.
Syntax
history.previous
Property of
history object
Implemented in
Navigator 3.0
Tainted?
Yes
Description
The previous property reflects the URL that would
be used if the user chose Back from the Go menu. This property has a value
only if data tainting is enabled; if data tainting is not enabled,
previous has no value.
previous is a read-only property.
Examples
The following example determines whether
history.previous contains the string "NETSCAPE.COM". If it does, the
function myFunction is called.
if (history.previous.indexOf("NETSCAPE.COM") != -1) {
myFunction(history.previous)
}
See also
current,
next properties;
"Using data tainting for security"
prompt
Method. Displays a Prompt dialog box with a message and
an input field.
Syntax
prompt(message, [inputDefault])
Parameters
message is any string or a property of an existing
object; the string is displayed as the message.
inputDefault is a string, integer, or property of
an existing object that represents the default value of the input field.
Method of
window object
Implemented in
Navigator 2.0
Description
A prompt dialog box looks as follows:
Use the prompt method to display a dialog box that
receives user input. If you do not specify an initial value for
inputDefault, the dialog box displays "<undefined>."
Although prompt is a method of the window
object, you do not need to specify a windowReference when you call
it. For example, windowReference.prompt()
is unnecessary.
You cannot specify a title for a prompt dialog box, but
you can use the open method to create your own "prompt" dialog. See
open (window object).
Examples
prompt("Enter the number of cookies you want to order:", 12)
See also
alert,
confirm methods
protocol
Property. A string specifying the beginning of the URL,
up to and including the first colon.
Syntax
1. links[index].protocol
2. location.protocol
3 areaName.protocol
Parameters
index is an integer representing a Link object
or the name of a Link object as specified by the NAME attribute.
areaName is the value of the NAME attribute of an
Area object.
Property of
Area object (see Link
object), Link object,
location object
Implemented in
-
-
Navigator 2.0
-
Navigator 3.0: property of Area
Tainted?
Yes
Description
The protocol property specifies a portion of the
URL. The protocol indicates the access method of the URL. For example, a
protocol of "http:" specifies HyperText Transfer Protocol, and a protocol
of "javascript:" specifies JavaScript code.
You can set the protocol property at any time, although
it is safer to set the href property to change a location. If the
protocol that you specify cannot be found in the current location, you will
get an error.
In event handlers, you must specify
window.location.protocol
instead of simply using
location.protocol
. Due to the scoping of static objects in
JavaScript, a call to location
without specifying an object
name is equivalent to document.location
, which is a synonym
for document.URL
.
The protocol property represents the scheme name
of the URL. See Section 2.1 of
RFC
1738 for complete information about the protocol.
Examples
See the examples for the
href property.
See also
hash,
host,
hostname,
href,
pathname,
port, search
properties
prototype
Property. Defines a property that is shared by all objects
of the specified type.
Syntax
objectType.prototype.propertyName = value
Parameters
objectType is the name of a constructor or function
specifying an object type.
propertyName is the name of the property to be
created.
value is the property value initially assigned for
all objects of the specified objectType.
Property of
prototype is a property of any object created with
new, such as the following:
Implemented in
Navigator 3.0
Tainted?
No
Description
Use the prototype property to explicitly add properties
to objects created with the new operator.
For example, you can create Date objects by using
the Date() constructor and the new operator.
Date.prototype
refers to the prototype object for the Date()
constructor. If you set a property for the prototype, such as
Date.prototype.description
, then all objects created with Date()
will have the description property, even if the objects already
exist.
var today = new Date()
var birthday = new Date(95,12,17)
Date.prototype.description=null
today.description="Oh what a beautiful mornin\'"
birthday.description="The day you were born"
After you set a property for the prototype, all subsequent
objects created with Date() will have the property:
startDate=new Date()
startDate.description="Started the daily grind"
Examples
Example 1: Add a property to a user-defined object.
The following example uses the function Car to define a Car
object type. It then uses new to create myCar, an instance
of the object. The code Car.prototype.wheels=4
adds the
wheels property to all instances of the Car object.
function Car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
var myCar = new Car("Acura", "Integra", 1987)
Car.prototype.wheels = 4 // no 3-wheelers please!
if (myCar.wheels == 4)
document.write("The car myCar has ", myCar.wheels, " wheels.")
Example 2: Add a method to String objects. The following
example creates a method, str_rep, and uses the statement
String.prototype.rep = str_rep
to add the method to all
String objects. All objects created with new String()
then have that method, even objects already created. The example then creates
an alternate method and adds that to one of the String objects using
the statement s1.rep = fake_rep
. The str_rep method of
the remaining String objects is not altered.
var s1 = new String("a")
var s2 = new String("b")
var s3 = new String("c")
// Create a repeat-string-N-times method for all String objects
function str_rep(n) {
var s = "", t = this.toString()
while (--n >= 0) s += t
return s
}
String.prototype.rep = str_rep
// Display the results
document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa"
document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb"
document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc"
// Create an alternate method and assign it to only one String variable
function fake_rep(n) {
return "repeat " + this + n + " times."
}
s1.rep = fake_rep
document.write("<P>s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times."
document.write("<BR>s2.rep(4) is " + s2.rep(4)) // "bbbb"
document.write("<BR>s3.rep(6) is " + s3.rep(6)) // "cccccc"
This example produces the following output:
s1.rep(3) is aaa
s2.rep(5) is bbbbb
s3.rep(2) is cc
s1.rep(1) is repeat a1 times.
s2.rep(4) is bbbb
s3.rep(6) is cccccc
The function in this example also works on String
objects not created with the String() constructor. The following code returns
"zzz".
"z".rep(3)
See also
constructor property;
"Creating new objects"
[Next reference file]
file: /Techref/language/java/SCRIPT/ref_m-q.htm, 157KB, , updated: 2009/2/2 13:27, local time: 2024/12/11 19:45,
|
| ©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://sxlist.com/TECHREF/language/java/SCRIPT/ref_m-q.htm"> Math</A> |
Did you find what you needed?
|
.