Special Edition Using HTML 4: JavaScript Keyword Reference

Methods

Methods are functions and procedures used to perform an operation on an object, variable, or constant. With the exception of built-in functions, methods must be used with an object:

```object.method()
```

Even if the method does not require any arguments, the parentheses are still required.

The object which utilizes the method is listed after the definition as "Method of object," followed by any cross-references to other methods. Standalone functions that are not used with objects are indicated with an asterisk (*).

abs  Returns the absolute (unsigned) value of its argument.

```document.write(Math.abs(-10));
document.write(Math.abs(12))
```

These examples return 10 and 12, respectively.

Method of Math.

acos  Returns the arc cosine (from zero to pi radians) of its argument. The argument should be a number between -1 and 1. If the value is outside the valid range, a zero is returned. Method of Math. See METHODS asin, atan, cos, sin, tan.

alert  Displays a JavaScript Alert dialog box with an OK button and a user-defined message. Before the user can continue, they must press the OK button. Method of window. See METHODS confirm and prompt.

anchor  Used with write or writeln methods, anchor creates and displays an HTML hypertext target. The syntax is:

```textString.anchor(anchorName)
```

where textString is what the user sees, and anchorName is equivalent to the name attribute of an HTML <anchor> tag.

Method of string. See link METHOD.

asin  Returns the arc sine (between -pi/2 and pi/2 radians) of a number between -1 and 1. If the number is outside the range, a zero is returned. Method of Math. See METHODS acos, atan, cos, sin, tan.

atan  Returns the arc tangent (between -pi/2 and pi/2 radians) of a number between -1 and 1. If the number is outside the range, a zero is returned. Method of Math. See METHODS acos, asin, cos, sin, tan.

back  Recalls the previous URL from the history list. This method is the same as history.go(-1). Method of history. See METHODS forward and go.

big  Formats a string object as a big font by encasing it with HTML <big> tags. Both of the following examples result in the same output--displaying the message "Welcome to my home page" in a big font:

```var welcomeMessage = "Welcome to my home page."
document.write(welcomeMessage.big())
```

Method of string. See METHODS fontsize, small.

blink  Formats a string object as a blinking line by encasing it with HTML <blink> tags. Both of the following examples produce a flashing line that says Notice:

```var attentionMessage = "Notice"
```

Method of string. See METHODS bold, italics, strike.

blur  Removes focus from the specified form element. For example, the following line removes focus from feedback:

```feedback.blur()
```

assuming that feedback is defined as:

```<input type="text" name="feedback">
```

Method of password, select, text, textarea. See METHODS focus and select.

bold  Formats a string object in bold text by encasing it with HTML <b> tags. Method of string. See METHODS blink, italics, strike.

ceil  Returns the smallest integer greater than, or equal to, its argument. For example:

```Math.ceil(1.01)
```

returns a 2.

Method of Math. See floor METHOD.

charAt  Returns the character from a string at the specified index. The first character is at position zero and the last at length -1.

```var userName = "Bobba Louie"
```

returns an a.

Method of string. See METHODS indexOf and lastIndexOf.

clear  Clears the contents of a window, regardless of how the window was filled. Method of document. See METHODS close, open, write, writeln.

clearTimeout  Cancels a timeout set with the setTimeout method. A timeout is set using a unique timeout ID, which must be used to clear it:

```clearTimeout(waitTime)
```

Method of frame and window. See setTimeout METHOD.

click  Simulates a mouse click on the calling form element with the effect dependent on the type of element.

Form Element Action Button, Reset, and Same as clicking button. Submit

Radio Selects option button. Checkbox Marks check box and sets value to on. Method of button, checkbox, radio, reset, submit.

close  For a document object, closes the current stream of output and forces its display. It also stops the browser winsock animation and displays Document: Done in the status bar. For a window object, closes the current window. As with all window commands, the window object is assumed. For example:

```window.close()
close()
self.close()
```

all close the current window.

Method of document and window. See METHODS clear, open, write, writeln.

confirm  Displays a JavaScript confirmation dialog box with a message and buttons for OK and Cancel. Confirm returns a true if the user selects OK and false for Cancel. The following example closes and loads a new window if the user presses OK:

```
if (confirm("Are you sure you want to enter.") {
tourWindow =
window.open("http:\\www.haunted.com\","hauntedhouse")
}
```

Method of window. See METHODS alert and prompt.

cos  Returns the cosine of the argument. The angle's size must be expressed in radians. Method of Math. See METHODS acos, asin, atan, sin, tan.

escape*  Returns ASCII code of its argument based on the ISO Latin-1 character set in the form %xx, where xx is the ASCII code. It is not associated with any other object, but is actually part of the JavaScript language. See unescape METHOD.

eval*  This built-in function takes a string or numeric expression as its argument. If a string, it attempts to convert it to a numeric expression. Eval then evaluates the expression and returns the value.

```var x = 10
var y = 20
document.write(eval("x + y"))
```

This method can also be used to perform JavaScript commands included as part of a string.

```var doThis = "if (x==10)
function checkMax () {
x++;
eval(doThis)
}
```

This can be useful when converting a date from a form (always a string) into a numerical expression or number.

exp  Returns e (Euler's constant) to the power of the argument to compute a natural logarithm. Method of Math. See METHODS log and pow.

Formats the calling string into a fixed-pitch font by encasing it in HTML <tt> tags.

Method of string.

floor  Returns the integer less than, or equal to, its argument. For example:

```Math.floor(2.99)
```

returns a 2.

Method of Math. See ceil METHOD.

focus  Navigates to a specific form element and gives it focus. From that point, a value can be entered by JavaScript commands or the user can complete the entry. Method of password, select, text, textarea. See METHODS blur and select.

fontcolor  Formats the string object to a specific color expressed as a hexadecimal RGB triplet or a string literal, similar to using <font color=color>. Method of string.

fontsize  Formats the string object to a specific font size: one of the seven defined sizes using an integer through the <fontsize=size> tag. If a string is passed, the size is changed relative to the value set in the <basefont> tag. Method of string. See METHODS big and small.

forward  Loads the next document on the URL history list. This method is the same as history.go(1). Method of history. See methods back and go.

getDate  Returns the day of the month as an integer between 1 and 31. Method of Date.

See setDate method.

getDay  Returns the day of the week as an integer from zero (Sunday) to six (Saturday). There is not a corresponding setDay command because the day is automatically computed when the date value is assigned. Method of Date.

getHours  Returns the hour of the day in 24-hour format, from zero (midnight) to 23 (11 PM). Method of Date. See setHours METHOD.

getMinutes  Returns the minutes with an integer from zero to 59. Method of Date. See setMinutes METHOD.

getMonth  Returns the month of the year as an integer between zero (January) and 11 (December). Method of Date. See setMonth METHOD.

getSeconds  Returns the seconds in an integer from zero to 59. Method of Date. See setSeconds METHOD.

getTime  Returns an integer representing the current value of the date object. The value is the number of milliseconds since midnight, January 1, 1970. This value can be used to compare the length of time between two date values. For functions involving computation of dates, it is useful to define variables defining the minutes, hours, and days in milliseconds:

```var dayMillisec =
1000 * 60 * 60 * 24 //1,000 milliseconds
x 60 sec x 60 min x 24 hrs
var hourMillisec =
1000 * 60 * 60 //1,000 milliseconds
x 60 sec x 60 min
var minuteMillisec =
1000 * 60 //1,000 milliseconds
x 60 sec
```

Method of Date. See setTime METHOD.

getTimezoneOffset  Returns the difference in minutes between the client machine and Greenwich mean time. This value is a constant except for daylight savings time. Method of Date.

getYear  Returns the year of the date object minus 1900. For example, 1996 is returned as 96. Method of Date. See setYear METHOD. go  Loads a document specified in the history list by its URL or relative to the current position on the list. If the URL is incomplete, the closest match is used. The search is not case sensitive. Method of history. See METHODS back and forward.

indexOf  Returns the location of a specific character or string, starting the search from a specific location. The first character of the string is specified as zero and the last is the string's length-1. The syntax is:

```stringName.indexOf([character|string],
[startingPoint])
```

The startingPoint is zero by default.

Method of string. See METHODS charAt and lastIndexof.

isNaN*  For UNIX platforms only, this standalone function returns true if the argument is not a number. On all platforms except Windows, the parseFloat and parseInt return NaN when the argument is not a number. See METHODS parseFloat and parseInt.

italics  Formats a string object into italics by encasing it an HTML <I> tag. Method of string. See METHODS blink, bold, strike.

lastIndexOf  Returns the index of a character or string in a string object by looking backwards from the end of the string or a user-specified index. Method of string. See METHODS charAt and indexOf.

link  Creates a hypertext link to another URL by defining the <href> attribute and the text representing the link to the user. Method of string. See anchor METHOD.

log  Returns the natural logarithm (base e) of a positive numeric expression greater than zero. An out-of-range number always returns -1.797693134862316e+308. Method of Math. See METHODS exp and pow.

max  Returns the greater of its two arguments. For example:

```Math.max(1,100)
```

returns 100.

Method of Math. See min METHOD.

min  Returns the lesser of its two arguments. Method of Math. See max METHOD.

open  For a document, opens a stream to collect the output of write or writeln methods. If a document already exists in the target window, then the open method clears it. The stream is ended by using the document.close() method. For a window, it opens a new browser window in a similar fashion to choosing File, New Web Browser from the Netscape menu. Using the URL argument, it loads a document into the new window; otherwise, the new window is blank. When used as part of an event handler, the form must include the window object; otherwise, the document is assumed. Window features are defined by a comma-separated list of options with =1 or =yes to enable and =0 or =no to disable. Window features include toolbar, location, directories, status, menubar, scrollbars, resizable, copyhistory, width and height.

Method of document and window. See METHODS clear, close, write, writeln.

parse  Takes a date string, such as Jan 11, 1996, and returns the number of milliseconds since midnight, Jan. 1, 1970. This function can be used to set date values based on string values. When passed a string with a time, it returns the time value. Because parse is a static function of Date, it is always used as Date.parse() rather than as a method of a created date object.

Method of Date. See UTC METHOD.

parseFloat*  Parses a string argument and returns a floating-point number if the first character is a plus sign, minus sign, decimal point, exponent, or a numeral. If it encounters a character other than one of the valid choices after that point, it returns the value up to that location and ignores all succeeding characters. If the first character is not a valid character, parseFloat returns one of two values based on the platform: Windows 0 NonWindows NaN See isNaN METHOD.

parseInt*  Parses a string argument and returns an integer based on a specified radix or base. A radix of 10 converts the value to a decimal, while eight converts to octal, and 16 to hexadecimal. Values greater than 10 for bases above 10 are represented with letters (A through F) in place of numbers. Floating-point values are converted to integers. The rules for evaluating the string are identical to parseFloat.

See isNaN and parseFloat METHODS.

pow  Returns a base raised to an exponent. Method of Math. See exp and log METHODS.

prompt  Displays a prompt dialog box that accepts user input. If an initial value is not specified for inputDefault, the dialog box displays the value <undefined>. Method of window. See alert and confirm METHODS.

random  On UNIX machines only, returns a pseudo-random number between zero and 1. Method of Math.

round  Returns the value of a floating-point argument rounded to the next highest integer if the decimal portion is greater than, or equal to, .5, or the next lowest integer is less than .5. Method of Math.

select  Selects the input area of a specified form element. Used in conjunction with the focus method, JavaScript can highlight a field and position the cursor for user input. Method of password, text, textarea. See METHODS blur and focus.

setDate  Sets the day of the month. Method of Date. See getDate METHOD.

setHours  Sets the hour for the current time. Method of Date. See getHours METHOD.

setMinutes  Sets the minutes for the current time. Method of Date. See getMinutes METHOD.

setMonth  Sets the month with an integer from zero (January) to 11 (December). Method of Date. See getMonth METHOD.

setSeconds  Sets the seconds for the current time. Method of Date. See getSeconds METHOD.

setTime  Sets the value of a date object. Method of Date. See getTime METHOD.

setTimeout  Evaluates an expression after a specified amount of time, expressed in milliseconds. This is not repeated indefinitely. For example, setting a timeout to three seconds will evaluate the expression once after three seconds--not every three seconds. To call setTimeout recursively, reset the timeout as part of the function invoked by the method. Calling the function startclock in the following example sets a loop in motion that clears the timeout, displays the current time, and sets the timeout to redisplay the time in one second.

```var timerID = null;
var timerRunning = false;
function stopclock () {
if(timerRunning) cleartimeout(timerID);
timerRunning=false;
}
function startclock () {
stopclock();
showtime();
}
function showtime () {
var now = new Date();
...
document.clock.face.value =   timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
```

Method of window. See clearTimeout METHOD.

setYear  Sets the year in the current date by using an integer representing the year minus 1900. Method of Date. See getYear METHOD.

sin  Returns the sine of an argument. The argument is the size of an angle expressed in radians, and the returned value is from -1 to 1. Method of Math. See METHODS acos, asin, atan, cos, tan.

small  Formats a string object into a small font by using the HTML <small> tags. Method of string. See METHODS big and fontsize.

sqrt  Returns the square root of a positive numeric expression. If the argument's value is outside the range, the returned value is zero.

strike  Formats a string object as strikeout text by using the HTML <strike> tags. Method of string. See METHODS blink, bold, italics.

sub  Formats a string object into subscript text by using the HTML <sub> tags. Method of string. See sup METHOD.

submit  Performs the same action as clicking a submit button. Method of form. See submit OBJECT; see onSubmit EVENT HANDLER.

substring  Returns a subset of a string object based on two indexes. If the indexes are equal, an empty string is returned. Regardless of order, the substring is built from the smallest index to the largest. Method of string.

sup  Formats a string object into superscript text by using the HTML <sup> tags. Method of string. See sub METHOD.

tan  Returns the tangent of an argument. The argument is the size of an angle expressed in radians. Method of Math. See METHODS acos, asin, atan, cos, sin.

toGMTString  Converts a date object to a string by using Internet Greenwich mean time (GMT) conventions. For example, if today is a date object:

```today.toGMTString()
```

then the string Mon, 18 Dec 1995 17:28:35 GMT is returned. Actual formatting may vary from platform to platform. The time and date is based on the client machine.

Method of Date. See toLocaleString METHOD.

toLocaleString  Converts a date object to a string by using the local conventions, such as mm/dd/yy hh:mm:ss. Method of Date. See toGMTString METHOD.

toLowerCase  Converts all characters in a string to lowercase. Method of string. See toUpperCase METHOD.

toString  Converts a date or location object to a string. Method of Date, location.

toUpperCase  Converts all characters in a string to uppercase. Method of string.

See toLowerCase method.

unEscape*  Returns a character based on its ASCII value expressed as a string in the format %xxx where xxx is a decimal number between zero and 255, or 0x0 to 0xFF in hex. See escape METHOD.

UTC  Returns the number of milliseconds for a date in Universal Coordinated Time (UTC) since midnight, January 1, 1970. UTC is a constant, and is always used as Date.UTC(), not with a created date object.

Method of Date. See parse METHOD.

write  Writes one or more lines to a document window, and can include HTML tags and JavaScript expressions, including numeric, string, and logical values. The write method does not add a new line (<br> or /n) character to the end of the output. If called from an event handler, the current document is cleared if a new window is not created for the output. Method of document. See METHODS close, clear, open, writeln.

writeln  Writes one or more lines to a document window followed by a new line character, and can include HTML tags and JavaScript expressions, including numeric, string, and logical values. If called from an event handler, the current document is cleared if a new window is not created for the output. Method of document. See methods close, clear, open, write.