Like every object-oriented programming language, JavaScript has several built-in or native objects that you, as a programmer, have access to. These objects are accessible anywhere in your program and will work the same way in any browser running in any operating system. That's not to say that each object behaves identically in any environment because that is not the case. Different browsers have implemented the JavaScript native objects in different ways. The object will run in the same way, producing similar, but not identical, output. This is yet another example of how encapsulation—hiding the internal workings of objects from the programmer—is very beneficial. Objects in different browsers have different internal workings, but they still accomplish the same tasks.
The following subsections list and describe all of the JavaScript objects and their properties and methods.
A Boolean object represents any value that is evaluated to be either true or false. Boolean objects generally are not used because the browser automatically creates them for you when a true/false value is encountered. There are three ways to create a Boolean object:
var myBoolean = new Boolean(); var myBoolean = new Boolean( <boolean value> ); var myBoolean = <boolean value>;
There is only one Boolean property, prototype. prototype is a static property of the Boolean object. Use the prototype property to assign new properties and methods to the Boolean object in the current document.
The Boolean objects have two methods, toString() and valueOf(). These two methods are inherited from the JavaScript base object Object and are part of every JavaScript object's definition.
toString(). Returns either "true" or "false" depending on the Boolean object's value.
valueOf(). Returns the boolean value of the Boolean object—either true or false.
An instance of a Date object is a snapshot of the date and time at which the object was created. A Date object's value is an integer value representing the number of milliseconds since zero hours at January 1, 1970. Negative values represent dates before that time, and positive values represent dates after that time. Following are several different ways to create a Date object:
var now = new Date(); var myDate = new Date( "month dd, yyyy, hh:mm:ss" ); var myDate = new Date( "month dd, yyyy" ); var myDate = new Date( yy, mm, dd, hh, mm, ss ); var myDate = new Date( yy, mm, dd ); var myDate = new Date( milliseconds );
The first method, var now = new Date();, creates a snapshot of the current date and time, while the subsequent ways create a date object with the specified date and time.
There is one Date property, prototype. prototype is a static property of the Date object. Use the prototype property to assign new properties and methods to the Date object in the current document.
The Date objects have many very useful methods for manipulating the value of the Date object. Here is a complete list and description of each.
getDate(). Returns an integer value representing the day of the month value of a Date object. Values are in the range of 1 to 31.
getDay(). Returns an integer value representing the day value of a Date object. Values are in the range of 0 to 6—Sunday = 0 and Saturday = 6.
getFullYear(). Returns an integer value representing the year value of a Date object. Netscape Navigator will not return a negative value, but Internet Explorer will.
getHours(). Returns an integer value representing the hours value of a Date object. Values are in the range of 0 to 23.
getMilliseconds(). Returns an integer value representing the milliseconds value of a Date object.
getMinutes(). Returns an integer value representing the minutes value of a Date object. Values are in the range of 0 to 59.
getMonths(). Returns an integer value representing the months value of a Date object. Values are in the range of 0 to 11.
getSeconds(). Returns an integer value representing the seconds value of a Date object. Values are in the range of 0 to 59.
getTime(). Returns an integer value representing the number of milliseconds since January 1, 1970 specified by the Date object.
getTimezoneOffset(). Returns the number of minutes that differ between GMT and client computer's clock. The zones to the west of GMT return a positive value while the zones to the east of GMT return a negative value. Return values are in the range of -720 to 720.
getUTCDate(). Returns the day of the month value of the UTC time stored internally by the browser in the range 1 to 31.
getUTCDay(). Returns the day value of the UTC time stored internally by the browser in the range 0 to 6 – Sunday = 0 and Saturday = 6.
getUTCFullYear(). Returns the year value of the UTC time stored internally by the browser.
getUTCHours(). Returns the hours value of the UTC time stored internally by the browser in the range 0 to 23.
getUTCMilliseconds(). Returns the milliseconds value of the UTC time stored internally by the browser in the range 0 to 999.
getUTCMinutes(). Returns the minutes value of the UTC time stored internally by the browser in the range 0 to 59.
getUTCMonth(). Returns the day value of the UTC time stored internally by the browser in the range 0 to 11.
getUTCSeconds(). Returns the seconds value of the UTC time stored internally by the browser in the range 0 to 59.
getYear(). Returns an integer specifying the last two digits of the year value of the Date object in the range 0 to 99 for years 1900 to 1999. This method behaves identically to the getFullYear() method with Date objects that have values after the year 2000.
parse(dateString). A static method that returns the number of milliseconds since
January 1, 1970 to the date specified in the dateString parameter.
setDate(dateInt). Sets the day of the month value for the original Date object. The operand must be in the range 1 to 31.
setFullYear(yearInt). Sets the year value for the original Date object.
setHours(hourInt). Sets the hours value for the original Date object. The operand must be in the range 1 to 23.
setMilliseconds(milliInt). Sets the day of the month value for the original Date object. The operand must be in the range 0 to 999.
setMinutes(minInt). Sets the minutes value for the original Date object. The operand must be in the range 0 to 59.
setMonth(monthInt). Sets the month value for the original Date object. The operand must be in the range 0 to 11.
setSeconds(secInt). Sets the seconds value for the original Date object. The operand must be in the range 0 to 59.
setTime(timeInt). Sets the Date object to the number of milliseconds since January 1, 1970.
setUTCDate(dateInt). Sets the day of the month value for the UTC time stored internally in the browser. The operand must be in the range 1 to 31.
setUTCFullYear(yearInt). Sets the year value for the UTC time stored internally in the browser.
setUTCHours(monthInt). Sets the hours value for the UTC time stored internally in the browser. The operand must be in the range 0 to 23.
setUTCMilliseconds(milliInt). Sets the milliseconds value for the UTC time stored internally in the browser. The operand must be in the range 0 to 999.
setUTCMinutes(minInt). Sets the minutes value for the UTC time stored internally in the browser. The operand must be in the range 0 to 59.
setUTCMonth(monthInt). Sets the month value for the UTC time stored internally in the browser. The operand must be in the range 0 to 11.
setUTCSeconds(secInt). Sets the seconds value for the UTC time stored internally in the browser. The operand must be in the range 0 to 59.
setYear(yearInt). Sets the year value of the original Date object. Use setFullYear() if your browser version allows it.
toGMTString(). Returns a string representation of the original Date object in the format:
dayAbbrev, dd mmm yyyy hh:mm:ss
Following is an example:
Mon 16 Feb 2003 03:37:06
toLocaleString(). Returns a string value of the original Date object in the format that may be localized for the particular country.
toString(). A static method used to convert the current date time to a string.
toUTCString(). Returns a string version of the UTC value of a Date object in the format:
dayAbbrev, dd mmm yyyy hh:mm:ss
Following is an example:
Mon 16 Feb 2003 03:37:06
UTC( yyyy, mm, dd, hh, mm, ss, msec ). A static method that returns a numeric version (not a Date object) of the date as stored internally by the browser. The return value is the number of milliseconds from January 1, 1970, to the specified date operands.
The Document object provides access to the HTML elements on a Web page. The Document object serves as the parent element for every HTML element on a page. Each window has a unique Document object.
alinkcolor. Gets and sets the default color of all active links on the page.
anchors. An array containing all anchors within the page. Use this property in the following way:
document.anchors["anchorID"];
applets. An array containing all applets within the page. Use this property in the following way:
document.applets["appletID"];
bgColor. Gets and sets the document's background color.
cookies. Returns a report on all visible and unexpired cookies for the page. Use this property in the following way:
document.cookies[= <expression>];
domain. Gets or sets the domain name from which the page originated.
embeds. An array containing all embeded tags within the page. Use this property in the following way:
document.embeds["embedID"];
fgColor. Gets or sets the documents foreground color.
formname. Used to reference a specific form on the page.
forms. An array containing all forms within the page. Use this property in the following way:
document.forms["formID"];
images. An array containing all images within the page. Use this property in the following way:
document.images["imageID"];
lastModified. Returns the date on which the page was last modified.
linkColor. Gets or sets the default color for links on the page.
links. An array containing all links within the page. Use this property in the following way:
document.links["linkID"];
plugins. An array containing all plugins within the page. Use this property in the following way:
document.plugins["pluginID"];
The plugins property is used with Netscape Navigator only.
referrer. Returns the URL for the page that referred the visitor to your page.
title. Returns the title of the page.
URL. Returns the page's full URL.
VlinkColor. Gets or sets the default color for all visited links on the page.
The Document object has many methods that are useful for performing an operation to an entire Web page. The following is a list of each method and its description:
captureEvent(event). Instructs the document to capture and handle all events of a certain type.
close(). Closes an output stream previously opened with document.open() and flushes the buffer to the screen.
getSelection(). Returns the contents of selected text on the document. Netscape only.
handleEvent(event). Calls the handler for the specified event's type.
open(mimeType, replace). Opens a stream to capture the output from the document.write() and document.writeln() methods.
releaseEvent(event). Instructs the document that the specified event type is to be captured further down the event hierarchy.
write(string). Writes the specified string onto the document.
writeln(string). Writes the specified string onto the document followed by a new line character.
Like all Web page elements, the Document object has many event handlers that you can use to capture and use events. Each event handler is listed and described here.
onClick. Captures the document's mouse click events. Syntax:
document.onClick = "<statements>";
onDblClick. Captures the document's double mouse click event. Syntax:
document.onDblClick = "<statements>";
onKeyDown. Captures the document's key-depress events. Syntax:
document.keyDown = "<statements>";
OnKeyPress. Captures the document's mouse-press events. Syntax:
document.onKeyPress = "<statements>";
onKeyUp. Captures the document's key up events. Syntax:
document.onKeyUp = "<statements>";
onMouseDown. Captures the document's mouse down events. Syntax:
document.onClick = "<statements>";
onMouseUp. Captures the document's mouse up events. Syntax:
document.onMouseUp = "<statements>";
An Event object is created automatically every time a Web page user presses a key or clicks his mouse button. Event objects can be captured and handled by event handlers.
Each Event object has several properties that you can use to identify the source and type of the event. Following is a complete list of their names and a description of each.
data. Returns an array that contains the URL of any dropped objects as stings. Netscape only.
height. The height of the window or frame that contains the element that initialized the event. Netscape only.
layerX/layerY. Synonyms for the x/y properties of the event object. Netscape only.
modifiers. Captures the document's mouse clicks. Netscape only. Syntax:
document.onClick = "<statements>";
pageX and pageY. These properties return the point at which the cursor was when the event occurred in relation to the page. Netscape only.
screenX/screenY. These properties return the point at which the cursor was when the event occurred in relation to the screen. Netscape only.
target. This property contains a reference to the object to which the event was originally sent. Netscape only.
type. This property returns a string containing the vent type, click, key down, etc.
which. This property returns the mouse button or key that was pressed. For the mouse, 1 = left button, 2 = middle button, and 3 = right button. For keys, this property is the ASCII value of the key. Netscape only.
width. The width of the window or frame that contains the element that initialized the event. Netscape only.
x/y. The horizontal/vertical position of the cursor at the time of the event in pixels relative to the layer that initialized the event.
The Math object is made up of several static methods used to perform mathematical operations for which there are no operators.
The Math object has many useful properties. Most of the properties of the Math object are constants that you might use in mathematical formulas.
E. Euler's Constant: 2.718281828459045
LN2. Natural logarithm of 2: 0.6931471805599453
LN10. Natural logarithm of 10: 02.302585092994046
LOG2E. Log base -2 of E: 0.6931471805599453
LOG10E. Log base -10 of E: 0.4342944819032518
PI3.141592653589793
SQRT1_2. The square root of 0.5: 0.7071067811865476
SQRT2. The square root of 2: 1.4142135623730951
The Math object also has many methods that are useful in mathematical formulas. The Math object is a static object, which means that you do not need to create an instance in order to call the methods. Each method may be called in the following way:
Math.<method name>( <arguments> );
abs(number). Returns the absolute value of number.
acos(number). Returns the arc cosine of number in radians.
asin(number). Returns the arc sine of number in radians.
atan(number). Returns the arc tangent of number in radians.
atan2(x,y). Returns the arctangent of the quotient of its two operands.
ceil(number). Returns the next highest integer from number.
cos(number). Returns the cosine of number in radians.
exp(number). Returns the value E raised to the power of number.
floor(number). Returns the next lowest integer from number.
max(n1, n2). Returns the larger of its two parameters.
min(n1, n2). Returns the lesser of its two parameters.
pow(n1, n2). Returns the first parameter raised to the power of the second parameter.
random(). Returns a pseudo-random number between 0 and 1. This method does not work in Netscape version 2.
round(number). Rounds a decimal number to its nearest integer value and returns it.
sin(number). Returns the sine of number in radians.
sqrt(number). Returns the square root of number.
tan(number). Returns the tangent of number in radians.
The Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.
The Number object contains several constant values that are often used for comparison. Here is a list of each property and its description.
MAX_VALUE. The largest possible value a number in JavaScript can have 1.7976931348623157E+308
MIN_VALUE. The smallest possible value a number in JavaScript can have 5E-324
NaN. Equal to a value that is not a number.
NEGATIVE_INFINITY. A value that is less than MIN_VALUE.
POSOTIVE_INFINITY. A value that is greater than MAX_VALUE.
prototype. A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document.
The Number object contains only the default methods that are part of every object's definition.
toString(). Returns the string representation of the number's value.
valueOf(). Returns the number's value.
The Object object is the base class for all other classes. Every property and method in this class also appears in all other classes.There is only one way to create an instance of an Object object:
var myObject = new Object();
The following subsections list and describe the Object class properties and methods.
There is only one Object class property, prototype. prototype is a static property of the Object class. Use the prototype property to assign new properties and methods to the Object class in the current document.
Objects only contain two methods, toString() and valueOf(). Each Object that extends this class will contain these two methods.
toString(). Returns the string representation of the object.
valueOf(). Returns the object's value.
The Screen object is most useful when trying to create a cross-platform Web page because it contains several properties that contain platform-specific information on the display screen's size and color depth.
The following properties of the Screen object allow a programmer to access platform-specific detail about the screen size and color depth of the client's computer.
availHeight. This property returns the height of the screen in pixels. The height of any components of the operating system's interface, such as the Windows Taskbar, is subtracted automatically.
availWidthxy. This property returns the width of the screen in pixels. The width of any components of the operating system's interface, such as the Windows Taskbar, is subtracted automatically.
colorDepth. This property represents the color depth of a color table, if one is in use. If no color table is being used, this property is the Screen.pixelDepth property.
height. This property returns the height of the screen in pixels.
pixelDepth. This property returns the color resolution of the display screen in bits per pixel.
width. This property returns the width of the screen in pixels.
The Window object is the top-level object in the JavaScript client hierarchy. Every browser window and frame has a window object. The Window object contains properties and methods describing and modifying the browser window and also contains a reference to the Document object contained in the browser.
The properties contained in the Window object can be used to identify the state of the browser window. Many of these properties are read-only, but others can be modified.
closed. This property is used to determine if the window has been closed. If the window has been closed, this property is true; otherwise, it is false. This property is read-only.
defaultStatus. This property is used to change the default message that is used in the status bar.
document. A reference to the Document object contained within the window.
This property is read-only.
frames. This property is an array containing all the named frames in the window.
This property is read-only.
history. A reference to the History object for this window. This property is read-only.
innerHeight/innerWidth. The dimensions of the display are in pixels. Netscape only. This property is read-only.
length. Identical to the value window. frames. length and represents the number of frames in the window. This property is read-only.
location. The current URL for the window.
locationbar. This property references the area of the browser into which the user types the URL. Setting the locationbar. visible boolean property will show/hide this portion of the browser. Netscape only.
menubar. This property references the area of the browser that contains the menus. Setting the menubar. visible boolean property will show/hide this portion of the browser. Netscape only.
name. This property is used to get or set the name of the window.
opener. This property references the window that opened the current window.
You can use window.opener.close() to close the window that opened the current one. This property is read-only.
outerheight/ outerwidth. The dimensions of the entire window in pixels.
pageXOffset/pageYOffset. The coordinates of the top-left corner of the window in relation to the desktop.
parent. This property references the parent of the current window. The parent is the window or frame that contains the current frame. This property is read-only.
personalbar. This property references the area of the browser that contains the user's custom links. Setting the personalbar.visible boolean property will show/hide this portion of the browser.
scrollbars. This property references the windows vertical and horizontal scrollbars. Setting the scrollbars.visible boolean property will show/hide this portion of the browser.
status. This property sets the message in the status bar for the current window.
statusbar. This property references the status bar portion of the window. Setting the statusbar.visible boolean property will show/hide this portion of the browser.
toolbar. This property references the tool bar portion of the window. Setting the toolbar.visible boolean property will show/hide this portion of the browser.
The Window object contains several static methods that can be called without first creating an instance of the Window object. To call one of the following methods, use the following syntax:
Window.<method name>( <arguments> ); or <method name>( <arguments> );
alert(string). Opens an alert dialog with the specified message.
back(). This method provides the same functionality as hitting the back button on the browser.
blur(). This method removes the focus from the Window object.
captureEvent( eventType). This method makes the window capture all events of the specified type.
clearInterval( intervalID). This method cancels a timeout previously set with the setInterval() method.
clearTimeout( intervalID). This method cancels a timeout previously set with the setTimeout() method.
close(). Used to close a window previously opened with the open() method.
confirt(string). This method opens a confirm dialog with the specified message and two buttons: OK, which returns true when pressed, and Cancel, which returns false when pressed.
disableExternalCapture(). This method disables the capturing of events previously set with the enableExternalCapturing() method.
enableExternalCapture(). This method allows the window to capture events occurring in a document loaded from a different server.
find(string, caseSensitive, backward). Opens the find dialog for the browser. The first argument is the string to search for and the last two are boolean values. All three arguments are optional, but if you specify either caseSensitive or backward, you must provide a value for the others.
focus(). This method gives focus to the window.
forward(). This method provides the same functionality as hitting the Forward button on the browser.
handleEvent( eventID). This method calls the handler for the specified event.
home(). This method provides the same functionality as hitting the home button on the browser.
moveBy(horizontal, vertical). This method moves the window the specified number of pixels from its current position.
moveTo(xPos, yPos). This method moves the window to specified x,y position on the screen.
open(URL, name, features). This method opens a new window with the specified URL, name, and features. The features include directories, height, location, menubar, resizable, scrollbars, status, toolbar, and width, each of which may be assigned the value yes or no.
The following is an example:
window.open( "http://www.somewhere.com", "myWindow", "width=400, height=400," + "resizable=no, toolbar=no" );
print(). This method opens the print dialog for the browser.
prompt(message, default). This method opens a prompt dialog with the specified answer and an optional default answer.
releaseEvents( eventType). This method releases any events of the specified type and sends them further down the event hierarchy.
resizeBy( horizontal, vertical). This method resizes the window by the specified amount.
routEvent( eventType). This method releases the specified event type back to the original target object or a sub-object of the window (a document).
scroll(). This method is deprecated; use scrollTo().
scrollBy(horizontal, vertical). This method scrolls the window by the specified amount in each horizontal and vertical direction.
scrollTo(xPos, yPos). This method scrolls the contents of the window. The x,y position located in the window's document becomes the top-left corner of the visible area.
setInterval( expression/function, milliseconds). This method is used to evaluate an expression or call a function at the specified interval.
setTimeout( expression/function, milliseconds). This method is used to evaluate an expression or call a function once, after the specified delay.
stop(). This method provides the same functionality as hitting the Stop button on the browser.
The Window object contains several event handlers that can capture events anywhere on the browser. The following is a list of their names and descriptions of each.
onBlur. This event handler executes the specified JavaScript code on the occurrence of the Blur event:
window.onBlur="JavaScript Statements"
onDragDrop. This event handler executes the specified JavaScript code on the occurrence of the DragDrop event:
window.onDragDrop="JavaScript Statements"
onError. This event handler executes the specified JavaScript code on the occurrence of the Error event:
window.onError="JavaScript Statements"
onFocus. This event handler executes the specified JavaScript code on the occurrence of the Focus event:
window.onFocus="JavaScript Statements"
onLoad. This event handler executes the specified JavaScript code on the occurrence of the Load event:
window.onLoad="JavaScript Statements"
onMove. This event handler executes the specified JavaScript code on the occurrence of the Move event:
window.onMove="JavaScript Statements"
onResize. This event handler executes the specified JavaScript code on the occurrence of the Resize event:
window.onResize="JavaScript Statements"
onUnload. This event handler executes the specified JavaScript code on the occurrence of the Unload event:
window.onUnload="JavaScript Statements"
These classes were created for the programmer's convenience. I encourage you to use them as often as possible in order to avoid reinventing the wheel, and to make all of your Web applications run in a similar fashion.