Developer.com Logo Click here to support our advertisers
Click here to support our advertisers
SHOPPING
JOB BANK
CLASSIFIEDS
DIRECTORIES
REFERENCE
Online Library
LEARNING CENTER
JOURNAL
NEWS CENTRAL
DOWNLOADS
COMMUNITY
CALENDAR
ABOUT US

Journal:

Get the weekly email highlights from the most popular journal for developers!
Current issue
developer.com
developerdirect.com
htmlgoodies.com
javagoodies.com
jars.com
intranetjournal.com
javascripts.com

All Categories : Java

Chapter 35

JavaScript Reference


CONTENTS


This chapter serves as a tutorial and reference guide for the JavaScript language. You'll learn about the objects and methods provided by JavaScript and learn how events are handled. By the end of this chapter, you should have an understanding of what JavaScript offers and be able to begin writing your own scripts.

JavaScript Objects

JavaScript is an object-based scripting language that does not support classes or inheritance. So, you might ask, how do you use JavaScript as an object-oriented language? Good question. JavaScript provides a number of default objects to which you have direct access, and allows you to create your own objects as well. The following are the JavaScript-supplied objects:

  • navigator can be thought of as being directly relational to the browser window. Inside the browser window lies the entire HTML document. The same holds true for the navigator object.
  • window is the parent class for all objects stored within the navigator object. Dialog boxes inside the navigator object's parent window can be created by using the properties and methods provided by the window object. The window object also provides access to the child windows of each frame through the frame's array property.
  • location holds all pertinent information about an URL.
  • history provides access to the browser's URL history list.
  • document contains information about all HTML properties inside the current page. It is through this object that JavaScript is enabled to output HTML.
  • form contains information about a form defined within the body of the HTML document.
  • button coincides with the button components displayed in the document.
  • checkbox coincides with the checkbox components displayed in the document.
  • text coincides with the text field components in the document.
  • textarea coincides with the text area components in the document.
  • hidden coincides with the hidden text field components in the document.
  • password coincides with the password text field components in the document.
  • radio coincides with the radio button components displayed in the document.
  • selections is an array containing all of the selection group components displayed in the document.
  • string provides a string container for JavaScript. A number of string-manipulation utilities are contained within the object as well.
  • Date provides the capability to store and work with date information.
  • Math provides mathematical constants and mathematical functions.

Properties and Methods

The power of JavaScript lies in the functionality provided to the programmer. The following sections are a reference to the methods and properties of the JavaScript objects. Keep in mind when programming JavaScript that it is a loosely typed language.

The navigator Object

The navigator object provides a base class for all HTML objects. It provides the basis for the logical hierarchy inherent in HTML. That is, the navigator object contains a window object containing the document object, which in turn contains all of the defined objects.

The window Object

The window object is the base object for the document object. It provides the following properties:

  • window frames[index] contains window objects for each frame child window.
  • number frames.length is the number of frame child windows.
  • window self is the current window object.
  • window parent is the parent window.
  • window top is the topmost ancestor window object.

The window object provides the following methods:

  • void alert(string "name") displays an alert dialog box containing the passed string.
  • boolean confirm(string "name") displays a confirmation dialog box containing the passed string. Returns a True or False value.
  • void open(string "URL", string "name") opens a new client window continuing the specified URL and displaying the title name.
  • void close() closes the self window.

The location Object

The location object provides information about the current URL location, as well as some useful methods. Its properties are the following:

  • string href holds the entire URL.
  • string protocol contains the protocol section of the URL, including the colon (:).
  • string host holds the hostname, including the optional port number embedded in the URL.
  • string hostname holds the hostname, not including the optional port number embedded in the URL.
  • string port contains the port of the host if specified; otherwise, the value is "" (null).
  • string path contains the path information that is specified in the URL after the host information.
  • string hash holds the CGI-specified information, if any.
  • string search contains the specified CGI parameters.
  • string post contains any post handler specified in the URL.

The location object provides the following methods:

  • string toString() returns the value stored in the href property.
  • void assign() sets the href property.

The history Object

The history object provides access to the browser's URL history list. Its properties are the following:

  • string back holds the URL of the previous location in the URL history list.
  • string forward holds the URL of the next location in the URL history list.
  • string current holds the URL of the current location in the URL history list.
  • int length contains the number of entries in the URL history list.

The history object provides the following methods:

  • void go(int delta) loads the URL in the URL history list that is delta distance from the current position. The value of delta may be either positive or negative, allowing positive and negative movement.
  • void go(string "srchstring") loads the URL in the URL history list that contains the partial srchstring in either the URL or the title.
  • string toString() creates an HTML list of all the entries in the URL history list.

The document Object

The document object contains information about all HTML properties inside the current page. In addition to the standard properties provided, a member for each form in the document is provided with the name specified in the form's NAME attribute.

The following are the document object's provided properties:

  • string title holds the document's title. If one is not defined, the value is Untitled.
  • string location contains the document's full URL.
  • string lastmodified contains the last-modified date.
  • string loadedDate contains the date the document was loaded.
  • string referer holds the name of the host that referred the current document.
  • string bgColor contains the 24-bit RGB hexadecimal background color.
  • string fgColor contains the 24-bit RGB hexadecimal foreground color.
  • string linkColor contains the 24-bit RGB hexadecimal hyperlink color.
  • string vlinkColor contains the 24-bit RGB hexadecimal visited hyperlink color.
  • string alinkColor contains the 24-bit RGB hexadecimal active hyperlink color. An active hyperlink is displayed when the mouse button has been depressed but has not been released.
  • form forms[index] is an array of form objects corresponding to the forms defined in the current document.
  • int forms.length contains the number of forms in the forms[] array.
  • location links[index] is an array of location objects corresponding to the links defined in the current document.
  • links.length contains the number of forms in the links[] array.
  • string anchors[index] is an array of anchor name strings, corresponding to the anchors defined in the current document.
  • anchors.length contains the number of forms in the anchors[] array.

The document object provides the following methods:

  • void write(string "output") outputs the output string into the current document.
  • void writeln(string "output") outputs the output string into the current document followed by a newline character.
  • void clear() clears the current document window.
  • void close() closes the current document window.

The form Object

The form object contains information about the defined form. In addition to its standard properties, this object contains a member for each field of the form. For instance, suppose a form contains a field called "Name"; the associated form would contain a member named Name. The value of the field can be obtained using form.Name.value.

The form object's default properties are the following:

  • string name contains the form's NAME attribute.
  • int method will contain a value of 0 if the form's METHOD attribute is equal to get, or a value of 1 if the METHOD attribute is equal to post.
  • string action holds the value of the ACTION attribute.
  • window target is the window to be used to display the form's response.
  • object elements[index] is an array containing all the component elements of the form.
  • elements.length contains the number of objects in the elements[] array.

The form object has no methods.

The button Object

The button object may take one of three separate functions coinciding with a form's reset button, submit button, or a custom button. The button object's properties are as follows:

  • string value stores the value specified in the VALUE attribute.
  • string name holds the value specified in the NAME attribute.

The button object contains no methods.

The checkbox Object

The checkbox object corresponds to a form's checkbox. Its properties are as follows:

  • string value stores the value specified in the VALUE attribute.
  • string name holds the value specified in the NAME attribute.
  • boolean status contains the current status of the checkbox.
  • boolean defaultstatus contains the default status of the checkbox specified in the CHECKED attribute.

The checkbox object contains no methods.

The text, textarea, hidden, and password Objects

The text, textarea, hidden, and password objects are all formed from the same object structure. The following are the properties of the shared object structure:

  • string value stores the value specified in the VALUE attribute.
  • string name holds the value specified in the NAME attribute.
  • string defaultValue holds the default value specified in the DEFAULTVALUE attribute.

The shared object structure contains these methods:

  • void focus() sets the focus to the object.
  • void blur() takes away the focus from the object.
  • void select() selects the content of the object's input field.

The radio Object

The radio object corresponds to a form's radio button. The object's properties are as follows:

  • string value stores the value specified in the VALUE attribute.
  • string name holds the value specified in the NAME attribute.
  • int index contains the zero-based index of the button.
  • boolean status contains the status of the radio button.
  • boolean defaultstatus contains the default status of the radio button specified in the CHECKED attribute.

The radio object contains no methods.

The select Object

The select object is an array corresponding to a form's selection list. Each element of the array contains the following properties:

  • string value stores the value specified in the VALUE attribute.
  • string text holds the value specified in the <OPTION> tag.
  • int index contains the zero-based index of the option.
  • boolean status contains the selection status of the item. True if selected.
  • boolean defaultstatus contains the default status of the selected item specified in the SELECTED attribute.

The select object contains no methods.

The string Object

The string object provides the capability to store string data and provides methods to manipulate the string value. length identifies the length of the string.

string offers the following methods:

  • void anchor(string "AnchorName") creates an anchor with the specified name.
  • void link(string "LinkAttribute") creates a link with the specified attribute.
  • void big() causes the text to be displayed with the <BIG> tag.
  • void small() causes the text to be displayed with the <SMALL> tag.
  • void sub() causes the text to be displayed in subscript as if it were inside a <SUB> tag.
  • void sup() causes the text to be displayed in superscript as if it were inside a <SUP> tag.
  • void blink() causes the text to be displayed blinking.
  • void bold() causes the text to be displayed bold.
  • void italics() causes the text to be displayed in italics.
  • void strike() causes the text to be displayed as if it were inside a <STRIKE> tag.
  • char charAt(int index) returns the character at the specified index value.
  • void fontcolor(Color) specifies the color in which to display the text.
  • void fontsize(int size) specifies the font size in which to display the text. The value is between 1 and 7.
  • int indexOf(string "SrchStrng",[beginIndex]) returns the starting index of SrchString. If beginIndex is specified, the search begins at the specified index position.
  • int lastIndexOf(string "SrchStrng",[beginIndex]) returns the starting index of the last occurrence found in SrchString. If beginIndex is specified, the search begins at the specified index position.
  • string substring(int begin, int end) returns a partial string, beginning at the begin location and ending at end.
  • string toLowerCase() returns the string in lowercase characters.
  • string toUpperCase() returns the string in uppercase characters.

The Date Object

The Date object provides access to the system date function and also is a container for date information.

The Date() function creates a Date object with the current system time.

The following examples create a Date object with the specified data:

Date("month day, year hours:minutes:seconds")

Date(year, month, day)
Date(year, month, day, hour)

The Date object has no properties.

The following are the methods for the Date object:

  • int getDate() returns the day of the month.
  • int getDay() returns the day of the week, starting with 0 for Sunday.
  • int getHours() returns the hour between 0 and 23.
  • int getMinutes() returns minutes.
  • int getMonth() returns the month of the year, starting with 0 for January.
  • int getSeconds() returns seconds.
  • int getTime() returns the number of milliseconds since January 1, 1970.
  • int getTimezoneOffset() returns the local time zone offset.
  • int getYear() returns the year.
  • int parse(sting "Date") returns the number of milliseconds since January 1, 1970.
  • void setDate(int date) sets the day of the month, between 0 and 31.
  • void setHours(int hour) sets the hour of the day, between 0 and 23.
  • void setMinutes(int minutes) sets the minutes in the hour, between 0 and 59.
  • void setMonth(int month) sets the month of the year, between 0 and 11.
  • void setSeconds(int seconds) sets the seconds of the hour, between 0 and 59.
  • void setTime(int tseconds) sets the time to the passed time value.
  • void setYear(int year) sets the year.
  • string toGMTString() returns the date in GMT string format.
  • string toLocaleString() returns the date to the current location's string format.
  • Date UTC(int year, month, day [, hrs] [, min] [, sec]) converts the passed parameters into a Date object.

The Math Object

The Math object provides defined math constants and some math functions. The following static constants are available:

  • E-The number e.
  • LN2-The natural logarithm of 2.
  • LN10-The natural logarithm of 10.
  • LOG2E-The logarithm base 2 of 10.
  • LOG10E-The logarithm base 10 of e.
  • PI-The pi constant.
  • SQRT1_2-The square root of 1/2.
  • SQRT2-The square root of 2.

The Math object provides the following mathematical functions:

  • abs is the absolute value function.
  • acos is the arccosine function.
  • asin is the arcsine function.
  • atan is the arctangent function.
  • ceil is the ceiling function.
  • cos is the cosine function.
  • exp is the exponential function.
  • floor is the floor function.
  • log is the natural logarithm function.
  • max is the maximum function.
  • min is the minimum function.
  • pow is the power function.
  • random is a random number generator.
  • round is the rounding function.
  • sin is the sine function.
  • sqrt is the square root function.
  • tan is the tangent function.

Handling Events

Handling events in JavaScript allows the script to be informed when an event has occurred. In Java, an event is trapped and then dispatched to the code that was intended to handle that event. In JavaScript, when an object is defined in the HTML, the function used to handle that event is specified with the object. For example, look at the example of placing a button into a document:

<INPUT TYPE="button" VALUE="OK" NAME="OKButton"
onClick="ValidateMe(this.form)">

The top line defines a button with a VALUE of "OK" and a NAME of "OKButton". The bottom line is what you want to understand here.

Notice the onClick parameter to the button. This line is associating the defined function ValidateMe with the onClick event of the button. This specifies to the code to handle the event directly from HTML.

JavaScript recognizes different event handlers for a number of supplied objects. The following are all the supported event handlers with their associated objects:

  • onBlur-select, text, textarea
  • onChange-select, text, textarea
  • onClick-button, checkbox, radio, link
  • onFocus-select, text, textarea
  • onLoad-window
  • onUnload-form
  • onMouseOver-link
  • onSelect-text, textarea
  • onSubmit-form

For all of these events, the syntax to define the event handler is the same. Inside the object's associated HTML tag is the event's name followed by the function you want to handle the event. For example, the following:

<BODY onLoad="sayHello("Hello To Me")>

sets the function sayHello to the onLoad event of the window object.

Arrays

The syntax to declare arrays in JavaScript is very different from Java, primarily due to the loose typing of JavaScript. Arrays are declared without specifying an implicit type; JavaScript resolves the type at a later time. For example, to declare a single-dimensional array, the syntax would be as follows:

var aBunchOfInts = new makearray(50);

The syntax to load the array would be like this:

ABunchofInts[0] = 1;

Due to the dynamic binding property of JavaScript, the type of the array is not set until a value is assigned.

Operators and Expressions

JavaScript follows the Java framework for operators and expressions. Binary operators are of the form operand1 operator operand2. Unary operators are of the form operator operand1 or operand1 operator. Bitwise operators convert operands into 32-bit integers before performing the operation.

The following are all valid JavaScript operators:

+
addition
-
subtraction
*
multiplication
/
division
%
modulus
++
increment
--
decrement
&&
and
||
or
!
not
==
equal to
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
!=
not equal to
&
bitwise AND
|
bitwise OR
^
bitwise XOR
>>
sign-propagating right shift
<<
left shift
>>>
zero fill right fill

JavaScript supports assignment expressions using = , evaluation expressions, and conditional expressions. Conditional expressions take the form (condition) ? val1 : val2, where val1 is processed if the condition is true; otherwise val2 is processed.

Statements

JavaScript provides conditional, loop, object-manipulation, and comment statements. The syntax for each of the statement types is identical to Java. The syntaxes for the JavaScript- supported statements are as follows:

Conditional Statements

  • if-else:
    if (condition) {
        statements1 }
    [else {
        statements2}]

Loop Statements

  • for:
    for ([initial-expression;] [condition;] [increment-expression]) {
        statements
    }
  • while:
    while (condition) {
        statements
    }
  • break:
    break
  • continue:
    continue

Object-Manipulation Statements

  • for   in:
    for (variable in object) {
        statements }
  • new:
    objectName = new objectType ( param1 [,param2] ...[,paramN] )
  • this:
    this[.propertyName]
  • with:
    with (object){
        statements
    }

Comment Statements

// comment text
/* multiple-line comment text */

Summary

The JavaScript language provides enough of a diversity from Java to retain its own identity. A large number of the statements, expressions, and operators are identical. However, the loose typing of JavaScript gives it a flavor all its own.



Ruler image
Contact reference@developer.com with questions or comments.
Copyright 1998 EarthWeb Inc., All rights reserved.
PLEASE READ THE ACCEPTABLE USAGE STATEMENT.
Copyright 1998 Macmillan Computer Publishing. All rights reserved.
Click here for more info

Click here for more info