The following methods and functions are available in JavaScript:
Returns the absolute value of a number.
Math.abs(number)
number is any numeric expression or a property of an existing object.
In the following example, the user enters a number in the first text box and presses the Calculate button to display the absolute value of the number.
<FORM> <P>Enter a number: <INPUT TYPE="text" NAME="absEntry"> <P>The absolute value is: <INPUT TYPE="text" NAME="result"> <P> <INPUT TYPE="button" VALUE="Calculate" onClick="form.result.value = Math.abs(form.absEntry.value)"> </FORM>
Returns the arc cosine (in radians) of a number.
Math.acos(number)
number is a numeric expression between -1 and 1, or a property of an existing object.
The acos method returns a numeric value between 0 and pi radians. If the value of number is outside the suggested range, the return value is always 0.
// Displays the value 0 document.write("The arc cosine of 1 is " + Math.acos(1)) // Displays the value 3.141592653589793 document.write("<P>The arc cosine of -1 is " + Math.acos(-1)) // Displays the value 0 document.write("<P>The arc cosine of 2 is " + Math.acos(2))
Displays an Alert dialog box with a message and an OK button.
alert("message")
message is any string or a property of an existing object.
Use the alert method to display a message that does not require a user decision. The message argument specifies a message that the dialog box contains.
Although alert is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.alert() is unnecessary.
In the following example, the testValue() function checks the name entered by a user in the text object of a form to make sure that it is no more than eight characters in length. This example uses the alert method to prompt the user to enter a valid value.
function testValue(textElement) { if (textElement.length > 8) { alert("Please enter a name that is 8 characters or less") } }You can call the testValue() function in the onBlur event handler of a form's text object, as shown in the following example:
Name: <INPUT TYPE="text" NAME="userName" onBlur="testValue(userName.value)">
Creates an HTML anchor that is used as a hypertext target.
text.anchor(nameAttribute)
text is any string or a property of an existing object.
nameAttribute is any string or a property of an existing object.
Use the anchor method with the write or writeln methods to programatically create and display an anchor in a document. Create the anchor with the anchor method, then call write or writeln to display the anchor in a document.
In the syntax, the text string represents the literal text that you want the user to see. The nameAttribute string represents the NAME attribute of the <A> tag.
Anchors created with the anchor method become elements in the anchors array. See the anchor object for information about the anchors array.
The following example opens the msgWindow window and creates an anchor for the Table of Contents:
The previous example produces the same output as the following HTML:
Returns the arc sine (in radians) of a number.
Math.asin(number)
number is a numeric expression between -1 and 1, or a property of an existing object.
The asin method returns a numeric value between -pi/2 and pi/2 radians. If the value of number is outside the suggested range, the return value is always 0.
// Displays the value 1.570796326794897 (pi/2) document.write("The arc sine of 1 is " + Math.asin(1)) // Displays the value -1.570796326794897 (-pi/2) document.write("<P>The arc sine of -1 is " + Math.asin(-1)) // Displays the value 0 because the argument is out of range document.write("<P>The arc sine of 2 is " + Math.asin(2))
Returns the arc tangent (in radians) of a number.
Math.atan(number)
number is either a numeric expression or a property of an existing object, representing the tangent of an angle.
The atan method returns a numeric value between -pi/2 and pi/2 radians.
// Displays the value 0.7853981633974483 document.write("The arc tangent of 1 is " + Math.atan(1)) // Displays the value -0.7853981633974483 document.write("<P>The arc tangent of -1 is " + Math.atan(-1)) // Displays the value 0.4636476090008061 document.write("<P>The arc tangent of .5 is " + Math.atan(.5))
Loads the previous URL in the history list.
history.back()
This method performs the same action as a user choosing the Back button in the Navigator. The back method is the same as history.go(-1).
<P><INPUT TYPE="button" VALUE="< Back" onClick="history.back()"> <P><INPUT TYPE="button" VALUE="> Forward" onClick="history.forward()">
Causes a string to be displayed in a big font as if it were in a <BIG> tag.
stringName.big()
stringName is any string or a property of an existing object.
Use the big method with the write or writeln methods to format and display a string in a document.
var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:
Hello, world
Causes a string to blink as if it were in a <BLINK> tag.
stringName.blink()
stringName is any string or a property of an existing object.
Use the blink method with the write or writeln methods to format and display a string in a document.
var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
Hello, world
Hello, world
Hello, world
Removes focus from the specified object.
1. passwordName.blur() 2. selectName.blur() 3. textName.blur() 4. textareaName.blur()
passwordName is either the value of the NAME attribute of a password object or an element in the elements array.
selectName is either the value of the NAME attribute of a select object or an element in the elements array.
textName is either the value of the NAME attribute of a text object or an element in the elements array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.
Use the blur method to remove focus from a specific form element.
password, select, text, textarea
The following example removes focus from the password element userPass:
userPass.blur()This example assumes that the password is defined as:
<INPUT TYPE="password" NAME="userPass">
Causes a string to be displayed as bold as if it were in a <B> tag.
stringName.bold()
stringName is any string or a property of an existing object.
Use the bold method with the write or writeln methods to format and display a string in a document.
var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
<BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>
Returns the least integer greater than or equal to a number.
Math.ceil(number)
number is any numeric expression or a property of an existing object.
//Displays the value 46 document.write("The ceil of 45.95 is " + Math.ceil(45.95)) //Displays the value -45 document.write("<P>The ceil of -45.95 is " + Math.ceil(-45.95))
Returns the character at the specified index.
stringName.charAt(index)
stringName is any string or a property of an existing object.
index is any integer from 0 to stringName.length - 1, or a property of an existing object.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.
var anyString="Brave new world" document.write("The character at index 0 is " + anyString.charAt(0)) document.write("The character at index 1 is " + anyString.charAt(1)) document.write("The character at index 2 is " + anyString.charAt(2)) document.write("The character at index 3 is " + anyString.charAt(3)) document.write("The character at index 4 is " + anyString.charAt(4))
Clears the document in a window.
document.clear()
The clear method empties the content of a window, regardless of how the content of the window has been painted.
When the following function is called, the clear method empties the contents of the msgWindow window:
function windowCleaner() { msgWindow.document.clear() msgWindow.document.close() }
Cancels a timeout that was set with the setTimeout method.
clearTimeout(timeoutID)
timeoutID is a timeout setting that was returned by a previous call to the setTimeout method.
See the description for the setTimeout method.
See the examples for the setTimeout method.
Simulates a mouse click on the calling form element.
1. buttonName.click() 2. radioName[index].click()
3. checkboxName.click()
buttonName is either the value of the NAME attribute of a button, reset, or submit object or an element in the elements array.
radioName is the value of the NAME attribute of a radio object or an element in the elements array.
index is an integer representing a radio button in a radio object.
checkboxName is either the value of the NAME attribute of a checkbox object or an element in the elements array.
The effect of the click method varies according to the calling element:
button, checkbox, radio, reset, submit
The following example toggles the selection status of the first radio button in the musicType radio object on the musicForm form:
document.musicForm.musicType[0].click()
The following example toggles the selection status of the newAge checkbox on the musicForm form:
document.musicForm.newAge.click()
Closes an output stream and forces data sent to layout to display.
document.close()
The close method closes a stream opened with the document.open() method. If the stream was opened to layout, the close method forces the content of the stream to display. Font style tags, such as <BIG> and <CENTER>, automatically flush a layout stream.
The close method also stops the "meteor shower" in the Netscape icon and displays "Document: Done" in the status bar.
function windowWriter1() { var myString = "Hello, world!" msgWindow.document.open() msgWindow.document.write(myString + "<P>") msgWindow.document.close() }
Closes the specified window.
windowReference.close()
windowReference is a valid way of referring to a window, as described in the window object.
The close method closes the specified window. If you call close without specifying a windowReference, JavaScript closes the current window.
In event handlers, you must specify window.close() instead of simply using close(). Due to the scoping of static objects in JavaScript, a call to close() without specifying an object name is equivalent to document.close().
Any of the following examples close the current window:
window.close() self.close() close()
The following example closes the messageWin window:
messageWin.close()
This example assumes that the window was opened in a manner similar to the following:
messageWin=window.open("")
Displays a Confirm dialog box with the specified message and OK and Cancel buttons.
confirm("message")
message is any string or a property of an existing object.
Use the confirm method to ask the user to make a decision that requires either an OK or a Cancel. The message argument specifies a message that prompts the user for the decision. The confirm method returns true if the user chooses OK and false if the user chooses Cancel.
Although confirm is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.confirm() is unnecessary.
This example uses the confirm method in the confirmCleanUp() function to confirm that the user of an application really wants to quit. If the user chooses OK, the custom cleanUp() function closes the application.
function confirmCleanUp() { if (confirm("Are you sure you want to quit this application?")) { cleanUp() } }You can call the confirmCleanUp() function in the onClick event handler of a form's pushbutton, as shown in the following example:
<INPUT TYPE="button" VALUE="Quit" onClick="confirmCleanUp()">
Returns the cosine of a number.
Math.cos(number)
number is a numeric expression representing the size of an angle in radians, or a property of an existing object.
The cos method returns a numeric value between -1 and 1, which represents the cosine of the angle.
//Displays the value 6.123031769111886e-017 document.write("The cosine of PI/2 radians is " + Math.cos(Math.PI/2)) //Displays the value -1 document.write("<P>The cosine of PI radians is " + Math.cos(Math.PI)) //Displays the value 1 document.write("<P>The cosine of 0 radians is " + Math.cos(0))
Returns the ASCII encoding of an argument in the ISO Latin-1 character set.
escape("string")
string is a non-alphanumeric string in the ISO Latin-1 character set, or a property of an existing object.
The escape function is not a method associated with any object, but is part of the language itself.
The value returned by the escape function is a string of the form "%xx", where xx is the ASCII encoding of a character in the argument. If you pass the escape function an alphanumeric character, the escape function returns the same character.
The following example returns "%26"
escape("&")
The following example returns "%21%23"
escape("!#")
The eval function evaluates a string and returns a value.
eval(string)string is any string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.
The eval function is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself.
The argument of the eval function is a string. Do not call eval to evaluate an arithmetic expression. JavaScript evaluates arithmetic expressions automatically. If the argument represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements.
If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3*x + 2", to a variable, and then calling eval at a later point in your script.
Both of the write statements below display 42. The first evaluates the string "x + y + 1", and the second evaluates the string "42".
var x = 2 var y = 39 var z = "42" document.write(eval("x + y + 1"), "
" ) document.write(eval(z), "
" )
In the following example, the getFieldName(n) function returns the name of the nth form element as a string. The first statement assigns the string value of the third form element to the variable field. The second statement uses eval to display the value of the form element.
var field = getFieldName(3) document.write("The field named ", field, " has value of ", eval(field + ".value"))
The following example uses eval to evaluate the string str. This string consists of JavaScript statements that opens an alert dialog box and assigns z a value of 42 if x is five, and assigns zero to z otherwise. When the second statement is executed, eval will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z.
var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; " document.write("z is ", eval(str))
Returns enumber, where number is the argument, and e is Euler's constant, the base of the natural logarithms.
Math.exp(number)number is any numeric expression or a property of an existing object.
//Displays the value 2.718281828459045 document.write("The value of e<SUP>1</SUP> is " + Math.exp(1))
Causes a string to be displayed in fixed-pitch font as if it were in a <TT> tag.
stringName.fixed()
stringName is any string or a property of an existing object.
Use the fixed method with the write or writeln methods to format and display a string in a document.
var worldString="Hello, world" document.write(worldString.fixed())
The previous example produces the same output as the following HTML:
<TT>Hello, world</TT>
Returns the greatest integer less than or equal to a number.
Math.floor(number)
number is any numeric expression or a property of an existing object.
//Displays the value 45 document.write("<P>The floor of 45.95 is " + Math.floor(45.95)) //Displays the value -46 document.write("<P>The floor of -45.95 is " + Math.floor(-45.95))
Gives focus to the specified object.
1. passwordName.focus() 2. selectName.focus() 3. textName.focus() 4. textareaName.focus()
passwordName is either the value of the NAME attribute of a password object or an element in the elements array.
selectName is either the value of the NAME attribute of a select object or an element in the elements array.
textName is either the value of the NAME attribute of a text object or an element in the elements array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.
Use the focus method to navigate to a specific form element and give it focus. You can then either programatically enter a value in the element or let the user enter a value.
password, select, text, textarea
In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the focus method returns focus to the password object and the select method highlights it so the user can re-enter the password.
function checkPassword(userPass) { if (badPassword) { alert("Please enter your password again.") userPass.focus() userPass.select() } }This example assumes that the password is defined as:
<INPUT TYPE="password" NAME="userPass">
Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.
stringName.fontcolor(color)
stringName is any string or a property of an existing object.
color is a string or a property of an existing object, expressing the color as a hexadecimal RGB triplet or as one of the string literals listed in Color Values.
Use the fontcolor method with the write or writeln methods to format and display a string in a document.
If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".
The fontcolor method overrides a value set in the fgColor property.
var worldString="Hello, world" document.write(worldString.fontcolor("maroon") + " is maroon in this line") document.write("<P>" + worldString.fontcolor("salmon") + " is salmon in this line") document.write("<P>" + worldString.fontcolor("red") + " is red in this line") document.write("<P>" + worldString.fontcolor("8000") + " is maroon in hexadecimal in this line") document.write("<P>" + worldString.fontcolor("FA8072") + " is salmon in hexadecimal in this line") document.write("<P>" + worldString.fontcolor("FF00") + " is red in hexadecimal in this line")
The previous example produces the same output as the following HTML:
<FONT COLOR="maroon">Hello, world</FONT> is maroon in this line <P><FONT COLOR="salmon">Hello, world</FONT> is salmon in this line <P><FONT COLOR="red">Hello, world</FONT> is red in this line <FONT COLOR="8000">Hello, world</FONT> is maroon in hexadecimal in this line <P><FONT COLOR="FA8072">Hello, world</FONT> is salmon in hexadecimal in this line <P><FONT COLOR="FF00">Hello, world</FONT> is red in hexadecimal in this line
Causes a string to be displayed in the specified font size as if it were in a <FONTSIZE=size> tag.
stringName.fontsize(size)
stringName is any string or a property of an existing object.
size is an integer between one and seven, or a string representing a signed integer between 1 and 7, or a property of an existing object.
Use the fontsize method with the write or writeln methods to format and display a string in a document. When you specify size as an integer, you set the size of stringName to one of the seven defined sizes. When you specify size as a string such as "-2", you adjust the font size of stringName relative to the size set in the <BASEFONT> tag.
var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:
<SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONTSIZE=7>Hello, world</FONTSIZE>
Loads the next URL in the history list.
history.forward()
This method performs the same action as a user choosing the Forward button in the Navigator. The forward method is the same as history.go(1).
<P><INPUT TYPE="button" VALUE="< Back" onClick="history.back()"> <P><INPUT TYPE="button" VALUE="> Forward" onClick="history.forward()">
Returns the day of the month for the specified date.
dateObjectName.getDate()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by getDate is an integer between 1 and 31.
The second statement below assigns the value 25 to the variable day, based on the value of the date object Xmas95.
Xmas95 = new Date("December 25, 1995 23:15:00") day = Xmas95.getDate()
Returns the day of the week for the specified date.
dateObjectName.getDay()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by getDay is an integer corresponding to the day of the week: zero for Sunday, one for Monday, two for Tuesday, and so on.
The second statement below assigns the value 1 to weekday, based on the value of the date object Xmas95. This is because December 25, 1995 is a Monday.
Xmas95 = new Date("December 25, 1995 23:15:00") weekday = Xmas95.getDay()
Returns the hour for the specified date.
dateObjectName.getHours()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by getHours is an integer between 0 and 23.
The second statement below assigns the value 23 to the variable hours, based on the value of the date object Xmas95.
Xmas95 = new Date("December 25, 1995 23:15:00") hours = Xmas95.getHours()
Returns the minutes in the specified date.
dateObjectName.getMinutes()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by getMinutes is an integer between 0 and 59.
The second statement below assigns the value 15 to the variable minutes, based on the value of the date object Xmas95.
Xmas95 = new Date("December 25, 1995 23:15:00") minutes = Xmas95.getMinutes()
Returns the month in the specified date.
dateObjectName.getMonth()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by getMonth is an integer between zero and eleven. Zero corresponds to January, one to February, and so on.
The second statement below assigns the value 11 to the variable month, based on the value of the date object Xmas95.
Xmas95 = new Date("December 25, 1995 23:15:00") month = Xmas95.getDate()
Returns the seconds in the current time.
dateObjectName.getSeconds()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by getSeconds is an integer between 0 and 59.
The second statement below assigns the value 30 to the variable secs, based on the value of the date object Xmas95.
Xmas95 = new Date("December 25, 1995 23:15:30") secs = Xmas95.getSeconds()
Returns the numeric value corresponding to the time for the specified date.
dateObjectName.getTime()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00. You can use this method to help assign a date and time to another date object.
The following example assigns the date value of theBigDay to sameAsBigDay.
theBigDay = new Date("July 1, 1999") sameAsBigDay = new Date() sameAsBigDay.setTime(theBigDay.getTime())
Returns the time zone offset in minutes for the current locale.
dateObjectName.getTimezoneOffset()
dateObjectName is either the name of a date object or a property of an existing object.
The time zone offset is the difference between local time and GMT. Daylight savings time prevents this value from being a constant.
x = new Date() currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60
Returns the year in the specified date.
dateObjectName.getYear()
dateObjectName is either the name of a date object or a property of an existing object.
The value returned by getYear is the year less 1900. For example, if the year is 1976, the value returned is 76.
The second statement below assigns the value 95 to the variable year, based on the value of the date object Xmas95.
Xmas95 = new Date("December 25, 1995 23:15:00") year = Xmas95.getYear()
Loads a URL from the history list.
history.go(delta | "location")delta is an integer or a property of an existing object, representing a relative position in the history list.
The go method navigates to the location in the history list determined by the argument that you specify. You can interactively display the history list by choosing History from the Window menu. Up to 10 items in the history list are also displayed on the Go menu.
The delta argument is a positive or negative integer. If delta is greater than zero, the go method loads the URL that is that number of entries forward in the history list; otherwise, it loads the URL that is that number of entries backward in the history list. If delta is 0, Navigator reloads the current page.
The location argument is a string. Use location to load the nearest history entry whose URL contains location as a substring. The location to URL matching is case-insensitive. Each section of a URL contains different information. See the location object for a description of the URL components.
The following button navigates to the nearest history entry that contains the string "home.netscape.com":
<P><INPUT TYPE="button" VALUE="Go" onClick="history.go('home.netscape.com')">
The following button navigates to the URL that is three entries backward in the history list:
<P><INPUT TYPE="button" VALUE="Go" onClick="history.go(-3)">
Returns the index within the calling string object of the first occurrence of the specified value, starting the search at fromIndex.
stringName.indexOf(searchValue, [fromIndex])
stringName is any string or a property of an existing object.
searchValue is a string or a property of an existing object, representing the value to search for.
fromIndex is the location within the calling string to start the search from. It can be any integer from 0 to stringName.length - 1 or a property of an existing object.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1.
If you do not specify a value for fromIndex, JavaScript assumes 0 by default. If searchValue is not found, JavaScript returns -1.
var anyString="Brave new world" //Displays 8 document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) //Displays 10 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) //Displays 6 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) //Displays 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new"))
On Unix platforms, evaluates an argument to determine if it is "NaN" (not a number).
isNaN(testValue)
testValue is the value you want to evaluate.
The isNaN function is a built-in JavaScript function. It is not a method associated with any object, but is part of the language itself. isNaN is available on Unix platforms only.
On all platforms except Windows, the parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. The "NaN" value is not a number in any radix. You can call the isNaN function to determine if the result of parseFloat or parseInt is "NaN". If "NaN" is passed on to arithmetic operations, the operation results will also be "NaN".
The isNaN function returns true or false.
The following example evaluates floatValue to determine if it is a number, then calls a procedure accordingly.
floatValue=parseFloat(toFloat) if isNaN(floatValue) { notFloat() } else { isFloat() }
Causes a string to be italicized as if it were in an <I> tag.
stringName.italics()
stringName is any string or a property of an existing object.
Use the italics method with the write or writeln methods to format and display a string in a document.
var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
<BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>
Returns the index within the calling string object of the last occurrence of the specified value. The calling string is searched backwards, starting at fromIndex.
stringName.lastIndexOf(searchValue, [fromIndex])
stringName is any string or a property of an existing object.
searchValue is a string or a property of an existing object, representing the value to search for.
fromIndex is the location within the calling string to start the search from. It can be any integer from 0 to stringName.length - 1 or a property of an existing object.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1.
If you do not specify a value for fromIndex, JavaScript assumes stringName.length - 1 (the end of the string) by default. If searchValue is not found, JavaScript returns -1.
var anyString="Brave new world" //Displays 8 document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) //Displays 10 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) //Displays 6 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) //Displays 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new"))
Creates an HTML hypertext link that jumps to another URL.
linkText.link(hrefAttribute)
linkText is any string or a property of an existing object.
hrefAttribute is any string or a property of an existing object.
Use the link method with the write or writeln methods to programatically create and display a hypertext link in a document. Create the link with the link method, then call write or writeln to display the link in a document.
In the syntax, the linkText string represents the literal text that you want the user to see. The hrefAttribute string represents the HREF attribute of the <A> tag, and it should be a valid URL. Each section of a URL contains different information. See the location object for a description of the URL components.
Links created with the link method become elements in the links array. See the link object for information about the links array.
The following example displays the word "Netscape" as a hypertext link that returns the user to the Netscape home page:
var hotText="Netscape" var URL="http://www.netscape.com" document.open() document.write("Click to return to " + hotText.link(URL)) document.close()
The previous example produces the same output as the following HTML:
Click to return to <A HREF="http://www.netscape.com">Netscape</A>
Returns the natural logarithm (base e) of a number.
Math.log(number)number is any positive numeric expression or a property of an existing object.
If the value of number is outside the suggested range, the return value is always -1.797693134862316e+308.
//Displays the value 2.302585092994046 document.write("The natural log of 10 is " + Math.log(10)) //Displays the value 0 document.write("<P>The natural log of 1 is " + Math.log(1)) //Displays the value -1.797693134862316e+308 //because the argument is out of range document.write("<P>The natural log of 0 is " + Math.log(0))
Returns the greater of two numbers.
max(number1, number2)number1 and number2 are any numeric arguments or the properties of existing objects.
//Displays the value 20 document.write("The maximum value is " + Math.max(10,20)) //Displays the value -10 document.write("<P>The maximum value is " + Math.max(-10,-20))
Returns the lesser of two numbers.
min(number1, number2)number1 and number2 are any numeric arguments or the properties of existing objects.
//Displays the value 10 document.write("The minimum value is " + Math.min(10,20)) //Displays the value -20 document.write("<P>The minimum value is " + Math.min(-10,-20))
Opens a stream to collect the output of write or writeln methods.
document.open(["mimeType"])
mimeType specifies any of the following document types:
text/html text/plain image/gif image/jpeg image/x-bitmap plugInplugIn is any two-part plug-in MIME type that Netscape supports.
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.
mimeType is an optional argument that specifies the type of document to which you are writing. If you do not specify a mimeType, the open method assumes text/html by default.
Following is a description of mimeType:
function windowWriter1() { var myString = "Hello, world!" msgWindow.document.open() msgWindow.document.write("<P>" + myString) msgWindow.document.close() }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")
Opens a new web browser window.
[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])
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.
pixels is a positive integer specifying the dimension in pixels.
The open method opens a new web browser window on the client, similar to choosing File|New Web Browser from the 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.
Following is a description of the windowFeatures:
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.
Notice the use of single quotes (') inside the onClick event handler.
Returns the number of milliseconds in a date string since January 1, 1970 00:00:00, local time.
Date.parse(dateString)dateString is a string representing a date or a property of an existing object.
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.
If IPOdate is an existing date object, then
IPOdate.setTime(Date.parse("Aug 9, 1995"))
Parses a string argument and returns a floating point number.
parseFloat(string)
string is a string that represents the value you want to parse.
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 one of the following values:
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".
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" or 0:
parseFloat("FF2")
Parses a string argument and returns an integer of the specified radix or base.
parseInt(string [,radix])
string is a string that represents the value you want to parse.
radix is an integer that represents the radix of the return value.
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 0, JavaScript assumes the following:
If the first character cannot be converted to a number, parseFloat returns one of the following values:
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".
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" or 0:
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")
Returns base to the exponent power, that is, baseexponent.
pow(base, exponent)base is any numeric expression or a property of an existing object.
//Displays the value 49 document.write("7 to the power of 2 is " + Math.pow(7,2)) //Displays the value 1024 document.write("<P>2 to the power of 10 is " + Math.pow(2,10))
Displays a Prompt dialog box with a message and an input field.
prompt(message, [inputDefault])message is any string or a property of an existing object; the string is displayed as the message.
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 the value <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.
prompt("Enter the number of cookies you want to order:", 12)
Returns a pseudo-random number between zero and one. This method is available on Unix platforms only.
Math.random()
//Displays a random number between 0 and 1 document.write("The random number is " + Math.random())
Returns the value of a number rounded to the nearest integer.
round(number)number is any numeric expression or a property of an existing object.
If the fractional portion of number is .5 or greater, the argument is rounded to the next highest integer. If the fractional portion of number is less than .5, the argument is rounded to the next lowest integer.
//Displays the value 20 document.write("The rounded value is " + Math.round(20.49)) //Displays the value 21 document.write("<P>The rounded value is " + Math.round(20.5)) //Displays the value -20 document.write("<P>The rounded value is " + Math.round(-20.5)) //Displays the value -21 document.write("<P>The rounded value is " + Math.round(-20.51))
Selects the input area of the specified password, text, or textarea object.
1. passwordName.select() 2. textName.select() 3. textareaName.select()
passwordName is either the value of the NAME attribute of a password object or an element in the elements array.
textName is either the value of the NAME attribute of a text object or an element in the elements array.
textareaName is either the value of the NAME attribute of a textarea object or an element in the elements array.
Use the select method to highlight the input area of a form element. You can use the select method with the focus method to highlight a field and position the cursor for a user response.
In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the select method highlights the password field and the focus method returns focus to it so the user can re-enter the password.
function checkPassword(userPass) { if (badPassword) { alert("Please enter your password again.") userPass.focus() userPass.select() } }This example assumes that the password is defined as:
<INPUT TYPE="password" NAME="userPass">
Sets the day of the month for a specified date.
dateObjectName.setDate(dayValue)
dateObjectName is either the name of a date object or a property of an existing object.
dayValue is an integer from 1 to 31 or a property of an existing object, representing the day of the month.
The second statement below changes the day for theBigDay to the 24th of July from its original value.
theBigDay = new Date("July 27, 1962 23:30:00") theBigDay.setDate(24)
Sets the hours for a specified date.
dateObjectName.setHours(hoursValue)
dateObjectName is either the name of a date object or a property of an existing object.
hoursValue is an integer between 0 and 23 or a property of an existing object, representing the hour.
theBigDay.setHours(7)
Sets the minutes for a specified date.
dateObjectName.setMinutes(minutesValue)
dateObjectName is either the name of a date object or a property of an existing object.
minutesValue is an integer between 0 and 59 or a property of an existing object, representing the minutes.
theBigDay.setMinutes(45)
Sets the month for a specified date.
dateObjectName.setMonth(monthValue)
dateObjectName is either the name of a date object or a property of an existing object.
monthValue is an integer between 0 and 11 (representing the months January through Decemeber), or a property of an existing object.
theBigDay.setMonth(6)
Sets the seconds for a specified date.
dateObjectName.setSeconds(secondsValue)
dateObjectName is either the name of a date object or a property of an existing object.
secondsValue is an integer between 0 and 59 or a property of an existing object.
theBigDay.setSeconds(30)
Sets the value of a date object.
dateObjectName.setTime(timevalue)
dateObjectName is either the name of a date object or a property of an existing object.
timevalue is an integer or a property of an existing object, representing the number of milliseconds since the epoch (1 January 1970 00:00:00).
Use the setTime method to help assign a date and time to another date object.
theBigDay = new Date("July 1, 1999") sameAsBigDay = new Date() sameAsBigDay.setTime(theBigDay.getTime())
Evaluates an expression after a specified number of milliseconds have elapsed.
timeoutID=setTimeout(expression, msec)
timeoutID is an identifier that is used only to cancel the evaluation with the clearTimeout method.
expression is a string expression or a property of an existing object.
msec is a numeric value, numeric string, or a property of an existing object in millisecond units.
The setTimeout method evaluates an expression after a specified amount of time. It does not evaluate the expression repeatedly. For example, if a setTimeout method specifies 5 seconds, the expression is evaluated after 5 seconds, not every 5 seconds.
Example 1. The following example displays an alert message 5 seconds (5,000 milliseconds) after the user clicks a button. If the user clicks the second button before the alert message is displayed, the timeout is cancelled and the alert does not display.
Example 2. The following example displays the current time in a text object. The showtime() function, which is called recursively, uses the setTimeout method update the time every second.
Sets the year for a specified date.
dateObjectName.setYear(yearValue)
dateObjectName is either the name of a date object or a property of an existing object.
yearValue is an integer greater than 1900 or a property of an existing object.
theBigDay.setYear(96)
Returns the sine of a number.
Math.sin(number)
number is a numeric expression or a property of an existing object, representing the size of an angle in radians.
The sin method returns a numeric value between -1 and 1, which represents the sine of the angle.
//Displays the value 1 document.write("The sine of pi/2 radians is " + Math.sin(Math.PI/2)) //Displays the value 1.224606353822377e-016 document.write("<P>The sine of pi radians is " + Math.sin(Math.PI)) //Displays the value 0 document.write("<P>The sine of 0 radians is " + Math.sin(0))
Causes a string to be displayed in a small font as if it were in a <SMALL> tag.
stringName.small()
stringName is any string or a property of an existing object.
Use the small method with the write or writeln methods to format and display a string in a document.
var worldString="Hello, world" document.write(worldString.small()) document.write("<P>" + worldString.big()) document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:
<SMALL>Hello, world</SMALL> <P><BIG>Hello, world</BIG> <P><FONTSIZE=7>Hello, world</FONTSIZE>
Returns the square root of a number.
Math.sqrt(number)number is any non-negative numeric expression or a property of an existing object.
If the value of number is outside the suggested range, the return value is always 0.
//Displays the value 3 document.write("The square root of 9 is " + Math.sqrt(9)) //Displays the value 1.414213562373095 document.write("<P>The square root of 2 is " + Math.sqrt(2)) //Displays the value 0 because the argument is out of range document.write("<P>The square root of -1 is " + Math.sqrt(-1))
Causes a string to be displayed as struck out text as if it were in a <STRIKE> tag.
stringName.strike()
stringName is any string or a property of an existing object.
Use the strike method with the write or writeln methods to format and display a string in a document.
var worldString="Hello, world" document.write(worldString.blink()) document.write("<P>" + worldString.bold()) document.write("<P>" + worldString.italics()) document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:
<BLINK>Hello, world</BLINK> <P><B>Hello, world</B> <P><I>Hello, world</I> <P><STRIKE>Hello, world</STRIKE>
Causes a string to be displayed as a subscript as if it were in a <SUB> tag.
stringName.sub()
stringName is any string or a property of an existing object.
Use the sub method with the write or writeln methods to format and display a string in a document.
var superText="superscript" var subText="subscript" document.write("This is what a " + superText.sup() + " looks like.") document.write("<P>This is what a " + subText.sub() + " looks like.")
The previous example produces the same output as the following HTML:
This is what a <SUP>superscript</SUP> looks like. <P>This is what a <SUB>subscript</SUB> looks like.
sup method
Submits a form.
formName.submit()
formName is the name of any form or an element in the forms array.
The submit method submits the specified form. It performs the same action as a submit button.
Use the submit method to send data back to an http server. The submit method returns the data using either "get" or "post", as specified in the method property.
The following example submits a form called musicChoice:
document.musicChoice.submit()
If musicChoice is the first form created, you also can submit it as follows:
document.forms[0].submit()
See also the example for the form object.
Returns a subset of a string object.
stringName.substring(indexA, indexB)
stringName is any string or a property of an existing object.
indexA is any integer from 0 to stringName.length - 1, or a property of an existing object.
indexB is any integer from 0 to stringName.length - 1, or a property of an existing object.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1.
If indexA is less than indexB, the substring method returns the subset starting with the character at indexA and ending with the character before indexB. If indexA is greater than indexB, the substring method returns the subset starting with the character at indexB and ending with the character before indexA. If indexA is equal to indexB, the substring method returns the empty string.
var anyString="Netscape" //Displays "Net" document.write(anyString.substring(0,3)) document.write(anyString.substring(3,0)) //Displays "cap" document.write(anyString.substring(4,7)) document.write(anyString.substring(7,4))
Causes a string to be displayed as a superscript as if it were in a <SUP> tag.
stringName.sup()
stringName is any string or a property of an existing object.
Use the sup method with the write or writeln methods to format and display a string in a document.
var superText="superscript" var subText="subscript" document.write("This is what a " + superText.sup() + " looks like.") document.write("<P>This is what a " + subText.sub() + " looks like.")
The previous example produces the same output as the following HTML:
This is what a <SUP>superscript</SUP> looks like. <P>This is what a <SUB>subscript</SUB> looks like.
Returns the tangent of a number.
Math.tan(number)
number is a numeric expression representing the size of an angle in radians, or a property of an existing object.
The tan method returns a numeric value which represents the tangent of the angle.
//Displays the value 0.9999999999999999 document.write("The tangent of pi/4 radians is " + Math.tan(Math.PI/4)) //Displays the value 0 document.write("<P>The tangent of 0 radians is " + Math.tan(0))
Converts a date to a string, using the Internet GMT conventions.
dateObjectName.toGMTString()
dateObjectName is either the name of a date object or a property of an existing object.
The exact format of the value returned by toGMTString varies according to the platform.
today.toGMTString()
In this example, the toGMTString method converts the date to GMT (UTC) using the operating system's time zone offset and returns a string value that is similar to the following form. The exact format depends on the platform.
Mon, 18 Dec 1995 17:28:35 GMT
Converts a date to a string, using the current locale's conventions.
dateObjectName.toLocaleString()
dateObjectName is either the name of a date object or a property of an existing object.
today.toLocaleString()
In this example, toLocaleString returns a string value that is similar to the following form. The exact format depends on the platform.
12/18/95 17:28:35
Returns the calling string value converted to lower case.
stringName.toLowerCase()
stringName is any string or a property of an existing object.
The toLowerCase method returns the value of stringName converted to lower case. toLowerCase does not affect the value of stringName itself.
The following examples both yield "alphabet".
var upperText="ALPHABET" document.write(upperText.toLowerCase()) "ALPHABET".toLowerCase()
Returns the calling string value converted to upper case.
stringName.toUpperCase()
stringName is any string or a property of an existing object.
The toUpperCase method returns the value of stringName converted to upper case. toUpperCase does not affect the value of stringName itself.
The following examples both yield "ALPHABET".
var lowerText="alphabet" document.write(lowerText.toUpperCase()) "alphabet".toUpperCase()
Returns the ASCII string for the specified value.
unescape("string")
string is a string or a property of an existing object, containing characters in either of the following forms:
The unescape function is not a method associated with any object, but is part of the language itself.
The string returned by the unescape function is a series of characters in the ISO Latin-1 character set.
The following example returns "&"
unescape("%26")
The following example returns "!#"
unescape("%21%23")
Returns the number of milliseconds in a date object since January 1, 1970 00:00:00, Universal Coordinated Time (GMT).
Date.UTC(year, month, day [, hrs] [, min] [, sec])
year is a year after 1900.
month is a month between 0-11.
date is a day of the month between 1-31.
hrs is hours between 0-23.
min is minutes between 0-59.
sec is seconds between 0-59.
UTC takes comma-delimited date parameters and returns the number of milliseconds since January 1, 1970 00:00:00, Universal Coordinated Time (GMT).
Because UTC is a static method of Date, you always use it as Date.UTC(), rather than as a method of a date object you created.
The following statement creates a date object using GMT instead of local time:
gmtDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0))
Writes one or more HTML expressions to a document in the specified window.
write(expression1 [,expression2], ...[,expressionN])expression1 through expressionN are any JavaScript expressions or the properties of existing objects.
The write method displays any number of expressions in a document window. You can specify any JavaScript expression with the write method, including numerics, strings, or logicals.
The write method is the same as the writeln method, except the write method does not append a newline character to the end of the output.
Use the write method within any <SCRIPT> tag or within an event handler. Event handlers execute after the original document closes, so the write method will implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open() method in the event handler.
var mystery = "world" // Displays Hello world testing 123 msgWindow.document.write("Hello ", mystery, " testing ", 123)In the following example, the write method takes two arguments. The first argument is an assignment expression, and the second argument is a string literal.
//Displays Hello world... msgWindow.document.write(mystr = "Hello "+ "world...")In the following example, the write method takes a single argument that is a conditional expression. If the value of the variable age is less than 18, the method displays "Minor". If the value of age is greater than or equal to 18, the method displays "Adult".
msgWindow.document.write(status = (age >= 18) ? "Adult" : "Minor")
Writes one or more HTML expressions to a document in the specified window and follows them with a newline character.
writeln(expression1 [,expression2], ...[,expressionN])expression1 through expressionN are any JavaScript expressions or the properties of existing objects.
The writeln method displays any number of expressions in a document window. You can specify any JavaScript expression, including numerics, strings, or logicals.
The writeln method is the same as the write method, except the writeln method appends a newline character to the end of the output. HTML ignores the newline character, except within certain tags such as <PRE>.
Use the writeln method within any <SCRIPT> tag or within an event handler. Event handlers execute after the original document closes, so the writeln method will implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open() method in the event handler.
All the examples used for the write method are also valid with the writeln method.