1. Math.propertyName 2. Math.methodName(parameters)
methodName is one of the methods listed below.
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)
}
|
|
|
|
|
|
|
Math.max(number1, number2)
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.
Number.MAX_VALUE
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.
if (num1 * num2 <= Number.MAX_VALUE) func1() else func2()
formName.method
You can set the method property at any time.
function getMethod() {
return document.musicForm.method
}
navigator.mimeTypes[index].propertyName
propertyName is one of the properties listed below.
The MimeType object is a member of the mimeTypes array; each Plugin object also has an array of MimeType objects.
For example, the following table summarizes the values for displaying JPEG images:
Each element of the mimeTypes array is a MimeType object.
1. navigator.mimeTypes[index] 2. navigator.mimeTypes.lengthindex 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.
| Property | Description |
|---|---|
| description | A description of the type |
| enabledPlugin | A reference to the Plugin object configured for the MIME type |
| type | The name of the MIME type, for example "video/mpeg or audio/x-wav" |
| suffixes | A string listing possible file name extensions for the MIME type, for example "mpeg, mpg, mpe, mpv, vbs, mpegv" |
The mimeTypes array has the following properties:
| Property | Description |
|---|---|
| length | Reflects the number of MIME types supported by the client |
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:
Math.min(number1, number2)
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.
Number.MIN_VALUE
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.
if (num1 / num2 >= Number.MIN_VALUE) func1() else func2()
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
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.
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.
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.
For Plugin: description, filename, length properties
Number.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.
var month = 13
if (month < 1 || month > 12) {
month = Number.NaN
alert("Month must be between 1 and 12.")
}
1. navigator.propertyName 2. navigator.methodName
methodName is one of the methods listed below.
| Property | Description |
|---|---|
| appCodeName | Specifies the code name of the browser |
| appName | Specifies the name of the browser |
| appVersion | Specifies version information for the Navigator |
| mimeTypes | An array of all MIME types supported by the client |
| plugins | An array of all plug-ins currently installed on the client |
| userAgent | Specifies the user-agent header |
|
|
|
Number.NEGATIVE_INFINITY
Because NEGATIVE_INFINITY is a constant, it is a read-only property of Number.
var smallNumber = -Number.MAX_VALUE*10 if (smallNumber == Number.NEGATIVE_INFINITY) func1() else func2()
history.next
if (history.next.indexOf("NETSCAPE.COM") != -1) {
myFunction(history.next)
}
numberObjectName = new Number()To use a Number object:
numberObjectName.propertyName
propertyName is one of the properties listed below.
The primary uses for the
Number object are:
| Property | Description |
|---|---|
| MAX_VALUE | The largest representable number |
| MIN_VALUE | The smallest representable number |
| NaN | Special "not a number" value |
| NEGATIVE_INFINITY | Special infinite value; returned on overflow |
| POSITIVE_INFINITY | Special negative infinite value; returned on overflow |
| prototype | Lets you add a properties to a Number object. |
biggestNum = Number.MAX_VALUE smallestNum = Number.MIN_VALUE infiniteNum = Number.POSITIVE_INFINITY negInfiniteNum = Number.NEGATIVE_INFINITY notANum = Number.NaNNote 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"
See the relevant objects for the onAbort syntax.
<IMG NAME="aircraft" SRC="f15e.gif"
onAbort="alert('You didn\'t get to see the image!')">
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.
<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>
Use the onChange event handler to validate data after it is modified by a user.
See the relevant objects for the onChange syntax.
<INPUT TYPE="text" VALUE="" NAME="userName" onChange="checkValue(this.value)">
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.
<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
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:
<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 definedExample 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>
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.
<INPUT TYPE="textarea" VALUE="" NAME="valueField" onFocus="valueCheck()">See also the examples for the onBlur event handler.
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.
<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.
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.
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.
<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 the relevant objects for the onReset syntax.
<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 the relevant objects for the onSelect syntax.
<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">
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.
<FORM onSubmit="return validate(this)"> ... </FORM>See also the examples for the Form object.
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).
<BODY onUnload="cleanUp()">
document.open(["mimeType"])
[windowReference.]document.open("text/html","replace")
"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.
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.
"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.
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")
[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])
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=pixelsYou may use any subset of these options. Separate options with a comma. Do not put spaces between the options. The windowFeatures are:
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.
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.
window.opener
This property persists across document unload in the opened window.
You can change the opener property at any time.
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=nullExample 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'
1. parent.propertyName 2. parent.methodName 3. parent.frameName 4. parent.frames[index]
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.
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.
Date.parse(dateString)
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.
IPOdate.setTime(Date.parse("Aug 9, 1995"))
parseFloat(string)
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."
parseFloat("3.14")
parseFloat("314e-2")
parseFloat("0.0314E+2")
var x = "3.14"
parseFloat(x)
The following example returns
"NaN":
parseFloat("FF2")
parseInt(string [,radix])
radix is an integer that represents the radix of the return value.
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:
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."
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")
<INPUT TYPE="password" NAME="passwordName" [VALUE="textValue"] SIZE=integer [onBlur="handlerText"] [onFocus="handlerText"]>
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.
1. passwordName.propertyName 2. passwordName.methodName(parameters) 3. formName.elements[index].propertyName 4. formName.elements[index].methodName(parameters)
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.
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.
| Property | Description |
|---|---|
| defaultValue | Reflects the VALUE attribute |
| form property | Specifies the form containing the Password object |
| name | Reflects the NAME attribute |
| type | Reflects the TYPE attribute |
| value | Reflects the current value of the Password object's field |
|
|
|
<B>Password:</B> <INPUT TYPE="password" NAME="password" VALUE="" SIZE=25>
1. links[index].pathname 2. location.pathname 3. areaName.pathname
areaName is the value of the NAME attribute of an Area object.
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.
Math.PI
function getPi() {
return Math.PI
}
1. navigator.plugins[index].propertyName 2. navigator.plugins[pluginIndex][mimeTypeIndex].mimeTypePropertyName
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.
The Plugin object is a member of the plugins array.
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 WindowsThe 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.
1. navigator.plugins[index] 2. navigator.plugins.lengthindex 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.
| Property | Description |
|---|---|
| description | A description supplied by the plug-in itself |
| filename | The name of the plug-in file on disk |
| length | The number of elements in the plug-in's array of MimeType objects |
| name | The name of the plug-in |
The plugins array has the following properties:
| Property | Description |
|---|---|
| length | Reflects the number of plug-ins installed on the client |
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"].descriptionExample 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"].lengthExample 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:
1. links[index].port 2. location.port 3 areaName.port
areaName is the value of the NAME attribute of an Area object.
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.
Number.POSITIVE_INFINITY
JavaScript does not have a literal for Infinity.
Because POSITIVE_INFINITY is a constant, it is a read-only property of Number.
var bigNumber = Number.MAX_VALUE * 10 if (bigNumber == Number.POSITIVE_INFINITY) func1() else func2()
Math.pow(base, exponent)
exponent is any numeric expression or a property of an existing object.
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).
history.previous
previous is a read-only property.
if (history.previous.indexOf("NETSCAPE.COM") != -1) {
myFunction(history.previous)
}
prompt(message, [inputDefault])
inputDefault is a string, integer, or property of an existing object that represents the default value of the input field.
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).
prompt("Enter the number of cookies you want to order:", 12)
1. links[index].protocol 2. location.protocol 3 areaName.protocol
areaName is the value of the NAME attribute of an Area object.
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.
objectType.prototype.propertyName = value
propertyName is the name of the property to be created.
value is the property value initially assigned for all objects of the specified objectType.
|
|
|
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"
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 ccccccThe function in this example also works on String objects not created with the String() constructor. The following code returns "zzz".
"z".rep(3)