Chapter 27

Manipulating Web Components Using JavaScript

by David Blankenbeckler


CONTENTS

In Chapter 26, "HTML and Web Page Design," you learned how to use HTML to create Web pages. This is fine for presenting information, but it does not really provide for a dynamic page that can respond to user events. Netscape created a scripting language called LiveScript to add this functionality. This language was later renamed JavaScript to capitalize on the popularity of the Java programming language. Though there are some similarities between Java and JavaScript, they are two separate languages.

JavaScript was designed to be a scripting language that can be embedded in HTML files. It is not compiled but instead interpreted by the browser. Unlike Java, which is first converted to easy-to-compile bytecodes, JavaScript is read by the browser as source code. This makes it easy for you to learn JavaScript by example because you can see how others are using JavaScript in their pages.

JavaScript is an object-based language, which means it includes many types of objects. An example is the Math object, which provides all sorts of mathematical functionality. However, JavaScript is not object oriented like C++ or Java because it does not support classes or inheritance.

JavaScript can respond to events such as form loading or unloading. This allows JavaScript to be a dynamic, interactive scripting language as opposed to a linear scripting language like MS-DOS batch files.

Like HTML and Java, JavaScript is designed to be platform independent; it will run on any platform that has a JavaScript-capable browser. Also like Java, JavaScript is designed to be secure. It is not possible for JavaScript to read or write to the user's files.

This chapter introduces the JavaScript programming language so that you can successfully implement JavaScript into your HTML files.

Using Scripts in HTML Files

Scripts are embedded in HTML files using the <SCRIPT>...</SCRIPT> pair of tags. The <SCRIPT> tags can appear in either the <HEAD> or <BODY> section of the HTML file. The advantage of placing it in the <HEAD> section is that it will be loaded and ready before the rest of the document loads.

The only attribute currently defined for the <SCRIPT> tag is LANGUAGE=, which is used to specify the scripting language. There are currently two values defined: "JavaScript" and "VBScript". For your JavaScript programs, use the following syntax:


<SCRIPT LANGUAGE="JavaScript">

// INSERT ALL JavaScript HERE

</SCRIPT>

Note
You might have noticed that the comment is not enclosed in normal <- and -> tags for HTML comments. This is because JavaScript supports the same style of comments as C and Java. Both the single-line // syntax and the /* ... */ syntax for multiple lines are supported

The difference in commenting syntax between HTML and JavaScript allows you to hide the JavaScript code inside an HTML comment so that older browsers that don't support it won't read it, as in the following example:


<SCRIPT LANGUAGE="JavaScript">

<!-- From here the JavaScript code is hidden

// INSERT ALL JavaScript HERE

// this is where the hiding ends -->

</SCRIPT>

The // is necessary on the last line of the script so that the browser will not try to interpret the line as JavaScript code. The examples in this chapter do not include the JavaScript hiding feature simply to make the code a little more readable.

A Simple <SCRIPT> Example

Let's start with a simple example to show you the JavaScript language and give you an idea of some of the things that are possible. The following program prompts the user for his name and then displays a short message using the name that was entered:


<HTML><HEAD>

<TITLE>A JavaScript Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var name = window.prompt("Hello! What is your name?","");

document.write("Hello " + name + "! I hope you like JavaScript!");

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Figure 27.1 shows the input prompt, and Figure 27.2 shows the output to the screen after you enter your name.

Figure 27.1 : A JavaScript example before you enter your name.

Figure 27.2 : A JavaScript example after you enter your name.

This example displays a prompt with the window.prompt method. The value obtained is stored in a variable called name. The variable is then combined with other strings and displayed in the browser's window using the document.write method.

Now that you have briefly glimpsed the functionality available through JavaScript, let's continue with a tutorial of the language itself.

Variables in JavaScript

A JavaScript variable must start with a letter or an underscore. A number cannot be used as the first character of a variable name but can be used after the first character. JavaScript is case sensitive.

There are two scopes available for variables: global and local. A global variable can be accessed anywhere in the application (HTML file). A local variable can be accessed only in the current function. Global variables are declared as follows:


x = 0;

A local variable is declared inside a function with the var keyword, as in the following:


var x = 0;

A global variable may use the var statement as well, but it is not necessary.

The following section discusses the types of data that can be assigned to variables in JavaScript.

Data Types

Unlike C++ or Java, JavaScript is a loosely typed language, meaning that you do not have to specify a data type when a variable is declared. The data types are automatically converted to the appropriate type as necessary.

Consider the following example:


<HTML><HEAD>

<TITLE>A Data Type Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var fruit = 'apples';

var numfruit = 12;

numfruit = numfruit + 20;

var temp = "There are " + numfruit + " " + fruit + ".";

document.write(temp);

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

JavaScript-enabled browsers will correctly handle this example with the following output:


There are 32 apples.

The JavaScript interpreter will treat the numfruit variable as an integer when 20 is added, and then as a string when it is combined with the temp variable.

The next section discusses the representation of values in JavaScript. The representation of a specific value is known as a literal.

Expressing Literals in JavaScript

Literals are values in a program that don't change. The following are examples of literals:

8
"The dog ate my shoe."
true

Note
In JavaScript there is no CONST type, as in Visual Basic and C, that can be used to represent some constant value; instead, it simply uses a variable.

The way in which values are represented in JavaScript is broken into four categories: integers, floating points, booleans, and strings. Each of these is discussed in the following sections.

Integer

Integers in JavaScript can be represented in three ways:

Floating Point

A floating point literal is composed of the following parts:

To be classified as a floating-point literal as opposed to an integer, there must be at least one digit followed by either a decimal point or E. The following are some examples of floating-point literals:

9.87
-0.85E4
9.87E14
.98E-3

Boolean

The boolean literal is used to indicate a true or false condition. There are two values:

true
false

String

A string literal is represented by zero or more characters enclosed in either single or double quotes (they must match at both ends!). The following are examples of string literals:

"the cat ran up the tree"
'the dog barked'
"100"

In order to represent a double quote in a string, simply use \". The following line of JavaScript code provides an example:


Document.Write("\"This text is inside quotes.\"");

Building Expressions in JavaScript

A set of literals, variables, or operators that evaluates to a single value is an expression. The single value can be a string, number, or boolean value. There are essentially three types of expressions in JavaScript:


(condition) ? valTrue : valFalse

If the condition evaluates to true, then the expression evaluates to valTrue; if false, the expression evaluates to valFalse. Here's an example:

state = (temp > 32) ? "liquid" : "solid"

In this example, the variable state would be assigned the value "liquid" if the variable temp were greater than 32; otherwise the value of state would be set to "solid".

Operators

Operators are used to perform some operation on data. An operator can return either a numeric value, a string value, or a boolean value to indicate true or false. The JavaScript operators are grouped into the following categories: assignment, comparison, arithmetic, string, logical, and bitwise logical.

Assignment

The assignment operator is the equal sign (=), which assigns the value of the right operand to the left operand. In addition, JavaScript supports several shortcut operators:

Normal Assignment
Shorthand Method
x = x + y
x += y
x = x - y
x -= y
x = x * y
x *= y
x = x / y
x /= y
x = x % y
x %= y

Comparison

The purpose of a comparison operator is to compare two operands and return true or false based on the comparison. The following comparison operators are supported by JavaScript:

Syntax
Description
==
Returns true if the operands are equal.
!=
Returns true if the operands are not equal.
>
Returns true if the left operand is greater than the right operand.
>=
Returns true if the left operand is greater than or equal to the right operand.
<
Returns true if the left operand is less than the right operand.
<=
Returns true if the left operand is less than or equal to the right operand.

Arithmetic

In addition to the standard operators (+, -, *, /) for addition, subtraction, multiplication, and division, JavaScript supports the following arithmetic operators:

SyntaxDescription
var1 % var2The modulus operator returns the remainder of the integer division of var1 by var2.
-The unary negation operator negates its operand.
Var++The increment operator adds one to var. This can also be represented by ++var.
var--The decrement operator subtracts one from var. This can also be represented by -var.

Note
If you are assigning the result of an increment or decrement to another variable such as y = x++, there are different results depending on whether the ++ or - appears before or after the variable name (x in this case). If the ++ or -- is used before x, then x would be incremented or decremented before the value of x is assigned to y. If the ++ or -- is after x, the value of x is assigned to y before it is incremented or decremented

String

When used with a string, the + operator becomes the concatenation operator and concatenates the two strings, as in the following:


"abc" + "xyz"

This code evaluates to abcxyz.

Logical

JavaScript supports the following logical operators:

SyntaxDescription
expr1 && expr2The logical AND operator, returns true if both expr1 and expr2 are true.
expr1 || expr2The logical OR operator, returns true if either expr1 or expr2 is true. Only if both are false will false be returned.
!exprThe logical NOT operator negates expr. It causes expr to become false if it was true and true if it was false.

Bitwise

For bitwise operations, the values are first converted to 32-bit integers and then evaluated bit by bit. The following operators are supported:

Syntax
Description
&
The bitwise AND operator compares each bit and returns 1 if both bits are 1.
|
The bitwise OR operator compares each bit and returns 1 if either of the bits is 1.
^
The bitwise XOR operator compares each bit and returns 1 if one and only one of the bits is 1.

There are also several bitwise shift operators. The value is converted to 32 bits before the shift operation. After the shift operation, the value is converted to the type of the left operand. The bitwise shift operators are as follows:

Syntax
Description
<<
The left shift operator, shifts the left operand the right operand number of bits to the left. For example, 4<<2 becomes 16 (100 binary becomes 10000 binary). Bits shifted to the left are discarded and zeros appear on the right in their place.
>>
The right shift operator, shifts the left operand the right operand number of bits to the right. For example, 16>>2 becomes 4 (10000 binary becomes 100 binary). Bits shifted to the right are discarded, and the sign of the left operator is preserved.
>>>
The zero-fill right shift operator, shifts the left operand the right operand number of bits to the right. The sign bit is shifted in from the left (unlike with the >> operator). Bits shifted to the right are discarded. For example, -8>>>2 becomes 1073741822 because the sign bit becomes part of the number. Of course, >>> and >> will yield the same result for positive numbers.

There are also some shortcut bitwise operators:

Normal AssignmentShorthand Method
x = x << yx <<= y
x = x >> yx >>= y
x = x >>> yx >>>= y
x = x & yx &= y
x = x ^ yx ^= y
x = x | yx |= y

Statements

The statements that are available in JavaScript can be grouped into the following categories:

Conditional Statements

Conditional statements provide the ability for a program to make a decision and perform specific actions based on the result of that decision. JavaScript provides this support through the if...else statement.

if...else

The if...else statement allows you to check for a certain condition and execute statements based on that condition. The optional else statement allows you to specify a set of statements to execute if the condition is not true.

Syntax

if (condition) {

   // statements for true condition 

}

else {

   // statements for false condition

}

Example

if (x == 10) {

   document.write("x is equal to 10, setting x=0.");

   x = 0; }

else

   document.write("x is not equal to 10.");

Note
The { and } characters are used to separate blocks of code. For example, notice that the { and } are used for the true condition in the previous example because there are two lines of statements. The false condition is only a one-line statement, so the { and } are not necessary

Loop Statements

Loop statements are a means of looping through a section of code until an expression evaluates to true. JavaScript provides two types of loop statements:

for

The for loop sets an initial expression, initExpr, then loops through a section of JavaScript statements as long as a condition expression evaluates to true. Each time through the loop the expression incrExpr is executed.

Syntax

for (initExpr; condition; incrExpr) {

   // statements to execute while looping

}

Example

for (x=1; x<=10; x++){

y = x * 25;

document.write("x="+ x + " y=" + y + "<BR>");

}

This example loops through the code until x is greater than 10. Figure 27.3 shows the output.

Figure 27.3 : A for loop example.

while

The while loop continues as long as a specified condition evaluates to true.

Syntax

while (condition) {

   // statement to execute while looping

}

Example

x = 1;

while (x <= 10) {

y = x * 25;

document.write("x="+ x + " y=" + y + "<BR>");

x++;

}

This produces the same result as the for loop example in Figure 27.3.

break

The break statement can be used to terminate the execution of a for or while loop. The program flow will continue at the statement following the end of the loop.

Syntax

break;

The following example loops until x is greater than or equal to 100. However, if the loop is entered with a value less than 50, the loop terminates and execution continues after the loop:


while (x < 100) {

   if (x < 50) break;

   x++;

}

continue

The continue statement is similar to the break statement except that execution is terminated and restarted at the beginning of the loop. For a while loop, control is returned to the condition. For a for loop, control is returned to the incrExpr.

Syntax

continue;

Example

The following example increments x from 0 to 5 and then skips to 8 and continues incrementing to 10:


x = 0;

while (x <= 10) {

  document.write("The value of x is " + x + "<BR>");

   if (x == 5) {

      x = 8;

      continue;

   }

   x++;

}

Object Manipulation Statements

As mentioned at the beginning of this chapter, JavaScript is an object-based language. JavaScript includes several statements that are designed to work with objects. The objects included in JavaScript are discussed later in this chapter.

for...in

The for...in statement is used to loop through all the properties of an object. The variable can be any arbitrary variable name; it is needed simply as something to refer to as you use the property in statements inside the loop. The following example should help you understand this statement.

Syntax

for (variable in object) {

   // statements

   }

Example

The following example cycles through all the properties of the Window object and prints the name of each property. Figure 27.4 shows the output:


<HTML><HEAD>

<TITLE>A For In Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

document.write("The properties of the Window object are: <BR>");

for (var x in window){

   document.write(x + "<BR>");

}

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Figure 27.4 : Output from the for...in example.

new

The new variable is used to create a new instance of an object.

Syntax

objectvar = new objecttype ( param1 [, param2] ... [,paramN] )

The following example creates an object called person that has the properties firstname, lastname, age, and sex. Note that the this keyword is used to refer to the object in the person function. Then two instances of person are created using the new statement:


<HTML><HEAD>

<TITLE>A New Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

function person(firstname, lastname, age, sex){

   this.firstname = firstname;

   this.lastname = lastname;

   this.age = age;

   this.sex = sex;

}

person1= new person("David", "Blankenbeckler", "27", "Male");

person2= new person("Kimberly", "Blankenbeckler", "27", "Female");

document.write("The first person's name is ", person1.firstname + ". <BR>");

document.write("The second person's name is ", person2.firstname + ".");

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

this

The this keyword is used to refer to the current object. The calling object is generally the current object in a method or function.

Syntax

this[.property]

Example

See the example for the new statement.

with

The with statement is used to set the default object for a series of statements so that you can refer to the properties without using the parent object.

Syntax

with(object){

   // statements

}

Example

The following example shows the use of the with statement to set the default object to document so that the write method can be used without having to refer to the document object itself, that is, document.write:


<HTML><HEAD>

<TITLE>A With Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

with (document) {

   write("This is an example of the things that can be done <BR>");

   write("with the <B>with</B> statement.<P>");

   write("This can really save some typing!");

}

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Functions

JavaScript supports the use of functions. While it's not necessary, a function can have one or more parameters and one return value. Because JavaScript is a loosely typed language, you do not need to define parameters or return types for a JavaScript function. A function can also be a property of an object, in which case it will act as a method for that object.

The function statement is used to create a function in JavaScript.

Syntax

function fnName([param1][,param2]...[,paramN]){

   // function statements

}

Example

The following example shows how to create and use a function as a member of an object. The printStats function is created as a method of the object person:


<HTML><HEAD>

<TITLE>A Function Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

function person(firstname, lastname, age, sex){

   this.firstname = firstname;

   this.lastname = lastname;

   this.age = age;

   this.sex = sex;

   this.printStats = printStats;   //makes printStats a method of person

}

function printStats(){

   document.write(this.firstname + " " + this.lastname + "'s stats are:<BR>");

   document.write("Age: " + this.age + "<BR>");

   document.write("Sex: " + this.sex + "<BR>");

}

person1= new person("David", "Blankenbeckler", "27", "Male");

person2= new person("Kimberly", "Blankenbeckler", "27", "Female");

person1.printStats();

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Built-In Functions

JavaScript contains several built-in functions, that is, functions that are built into the language itself and are not a part of an object:

These built-in functions are described in the following sections.

eval

The eval function is used to evaluate expressions or statements. Any expression, statement, or object properties can be evaluated. This is useful for evaluating expressions that are entered by the user (otherwise it could be evaluated directly).

Syntax

returnval = eval( any legal Java expressions or statements )

Example

<HTML><HEAD>

<TITLE>An Eval Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var string = "10 + Math.sqrt(64)";

document.write(string + " = " + eval(string));

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

parseInt

The parseInt function takes a string value and attempts to convert it to an integer of a base that's specified by an optional second parameter. This function can be used to convert different bases back to base 10 or to ensure that character-entered data is converted to integer before being used in calculations. In the case of bad input data, the parseInt function reads and converts a string until the point where it finds non-numeric characters. In addition, parseInt truncates floating-point numbers.

Syntax

parseInt(string [, radix]);

Example

<HTML><HEAD>

<TITLE>An parseInt Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

document.write("Converting 0xC hex to base-10: " + parseInt(0xC, 10) + "<BR>");

document.write("Converting 1100 binary to base-10: " + parseInt(1100, 2));

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

parseFloat

This built-in function is similar to the parseInt function except that it returns a floating point representation of string input.

Syntax

parseFloat(string);

Example

The following example shows how parseFloat works for several types of strings. Figure 27.5 shows the output:


<HTML><HEAD>

<TITLE>An parseFloat Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

document.write("This script will show how different strings are ");

document.write("converted using parseFloat.<BR>");

document.write("137 = " + parseFloat("137") + "<BR>");

document.write("137abc = " + parseFloat("137abc") + "<BR>");

document.write("abc137 = " + parseFloat("abc137") + "<BR>");

document.write("1abc37 = " + parseFloat("1abc37") + "<BR>");

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Figure 27.5 : Screen output from the parseFloat example.

Arrays

Although JavaScript has no explicit support for arrays, Netscape has published a method that allows you to make your own by creating a function that initializes the array as follows:


function InitArray(numElements) {

   this.length = numElements;

   for (var x = 1; x <= numElements; x++) {

       this[x] = 0 }

   return this;

}

This creates an array of the specified size and fills it with 0. Note that the first element is the length of the array and should not be used.

To create an array, type the following:


myArray = new InitArray(10);

This creates myArray[1] through myArray[10], with each element containing a 0. The array can be populated with data as follows:


myArray[1] = "South Carolina";

myArray[2] = "Oregon";

Here's a full example:


<HTML><HEAD>

<TITLE>An Array Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

function InitArray(numElements) {

   this.length = numElements;

   for (var x = 1; x <= numElements; x++) {

       this[x] = 0 }

   return this;

}

myArray = new InitArray(10);

myArray[1] = "South Carolina";

myArray[2] = "Oregon";

document.write(myArray[1] + "<BR>");

document.write(myArray[2] + "<BR>");

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Events

JavaScript is an event-driven language, which means it can respond to certain events, such as a mouse click or the loading of a document. An event can cause a section of code (known as an event handler) to execute to allow the program to respond appropriately.

Event Handlers

The section of code, or function, that responds to an event is called an event handler. The event handler is specified as an attribute of an HTML tag:


<tagName eventHandler="JavaScript Code or Function">

The following example calls the CheckAge() function when the value of the text field is changed:


<INPUT TYPE=TEXT NAME="AGE" onChange="CheckAge()">

The event handler code does not have to be a function; it can be JavaScript statements separated by semicolons. However, for purposes of modularity and code "cleanliness," it is typically a separate function.

The following event handlers are available in JavaScript:

EventDescription
onBlur Occurs when the input focus is removed from form element.
onClick Occurs when the user clicks form element or link.
onChange Occurs when the text, text area, or select element value is changed.
onFocus Occurs when the form element gets the focus.
onLoad Occurs when the page is loaded.
OnMouseOver Occurs when the mouse is moved over a link or anchor.
onSelect Occurs when the user selects a form element's input field.
onSubmit Occurs when the user submits a form.
onUnload Occurs when the user exits a page.

The following example shows a simple event handler script that validates a value entered into a text field. The user's age is entered in the field, and the event handler checks whether a valid age was entered. If not, a message will appear asking the user to re-enter the value. The event handler is called when the AGE field is changed and the focus is moved to another field. Figure 27.6 shows the screen output for the following code:


<HTML>

<HEAD>

<TITLE>An Event Handler Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

function CheckAge(form) {

   if ((form.age.value < 0) || (form.age.value > 120)) {

      alert("Please enter your real age!");

      form.age.value = 0;

   }

}

</SCRIPT>

</HEAD>

<BODY>

<FORM NAME="SURVEY">

Please enter your name and age:<BR>

First<INPUT TYPE=TEXT NAME="FNAME" MAXLENGTH=15 SIZE=10>

MI<INPUT TYPE=TEXT NAME="MI" MAXLENGTH=1 SIZE=1>

Last<INPUT TYPE=TEXT NAME="LNAME" MAXLENGTH=20 SIZE=15><BR><BR>

Age<INPUT TYPE=TEXT NAME="AGE" MAXLENGTH=3 SIZE=2 onChange="CheckAge(SURVEY)">

<P>

Please select your favorite season of the year:<BR>

Spring<INPUT TYPE=RADIO NAME="SEASON" VALUE="Spring">

Summer<INPUT TYPE=RADIO NAME="SEASON" VALUE="Summer">

Fall  <INPUT TYPE=RADIO NAME="SEASON" VALUE="Fall">

Winter<INPUT TYPE=RADIO NAME="SEASON" VALUE="Winter">

<P>

Please check all of the outdoor activities that you enjoy:<BR>

Hiking<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Hiking">

Skiing<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Sking">

Water Sports<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Water">

Cycling<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Cycling">

<P>

<INPUT TYPE=SUBMIT><INPUT TYPE=RESET>

</FORM>

</BODY>

</HTML>

Figure 27.6 : An event handler example.

JavaScript Objects

As mentioned at the beginning of the chapter, JavaScript is an object-based, not object-oriented, programming language, primarily because it does not support classes or inheritance. This section presents the objects available for your JavaScript programs. Figure 27.7 shows the JavaScript object hierarchy.

In the JavaScript object hierarchy, the descendant objects are actually properties of the parent object. For example, in the example for the event handler, the form, named SURVEY, would be a property of the document object, and the text field, named AGE, a property of the form. To reference the value of AGE, you could use the following:


document.SURVEY.AGE.value

Objects in JavaScript have properties, methods, and event handlers associated with them. For example, the document object has a title property. This property reflects the contents of the <TITLE> tag for the document. In addition, you have seen the document.write method used in many of the examples. This method is used to output text to the document.

Figure 27.7 : The JavaScript object hierarchy.

Objects can also have event handlers. For example, the links object has two event handlers, onClick and onMouseOver. The onClick event handler is invoked when a link object is clicked, and the onMouseOver is invoked when the mouse pointer passes over the link.

The properties, methods, and event handlers for each JavaScript object are described in the following sections.

The navigator Object

The navigator object is used to obtain information about the browser, such as the version number. It does not have any methods or event handlers associated with it.

Properties
appCodeName-Used to specify the internal code name of the browser (for example, Atlas).
AppName-Used to specify the name of the browser.
AppVersion-Used to specify version information for the navigator object.
userAgent-Used to specify the user-agent header.
Example

The following example displays each property of the navigator object:


<HTML><HEAD>

<TITLE>A Navigator Object Example</TITLE>

<SCRIPT LANGUAGE="JavaScript">

document.write("appCodeName = " + navigator.appCodeName+ "<BR>");

document.write("appName = " + navigator.appName + "<BR>");

document.write("appVersion = " + navigator.appVersion + "<BR>");

document.write("userAgent = " + navigator.userAgent + "<BR>");

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

The window Object

The window object is a top-level object. The document, frame, and location objects are all properties of the window object.

Properties
defaultStatus-The default message that is displayed in the window's status bar.
Frames-An array that reflects all the frames in a window.
Length-The number of frames in a parent window.
Name-The name of the current window.
Parent-The parent window object.
Self-The current window.
Status-Used for a temporary status message for the window's status bar. This is used to get or set the status message and overrides defaultStatus.
Top-The topmost window.
Window-The current window.
Methods
alert("message")-Displays a dialog box with the string "message" and an OK button.
clearTimeout(timeoutID)-Clears a timeout set by SetTimeout. SetTimeout returns timeoutID.
windowReference.close-Closes the window referred to by windowReference.
confirm("message")-Displays a dialog box with the string "message", an OK button, and a Cancel button. Returns true for OK and false for Cancel.
[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])-Opens a new window.
prompt("message" [,"defaultInput"])-Opens a dialog box with a text field for input.
TimeoutID = setTimeout(expression, msec)-Evaluates expression after msec has elapsed.
Event Handlers
onLoad-Occurs when a window finishes loading.
OnUnload-Occurs when a window is unloaded.

The location Object

The location object's properties contain information about the URL of the current document. This object does not have any methods or event handlers. Refer to the following sample URL in the property descriptions that follow:


http://www.abc.com/chap1/page2.html#topic3

Properties
hash-The current location's anchor name (for example, topic3).
Host-The hostname:port portion of the URL (for example, www.abc.com). Note that the port is typically the default port and is not shown.
Hostname-The host and domain name (for example, www.abc.com).
href-The entire URL for the current document.
Pathname-The path portion of the URL (for example, /chap1/page2.html).
port-The communications port used on the host computer, typically the default port.
Protocol-The protocol being used (with the colon) (for example, http:).
Search-A search query that may be at the end of a URL for a CGI script.

The frame Object

A window can have several frames. The frames can be scrolled independently, and each can have a unique URL. There are no event handlers for a frame. The onLoad and onUnload events are for the window object.

Properties
frames-An array of all the frames in a window.
Name-The <FRAME> tag's NAME attribute.
Length-The number of child frames within a frame.
Parent-The window or frame containing the current frameset.
self-The current frame.
Window-The current frame.
Methods
clearTimeout(timeoutID)-Clears a timeout set by SetTimeout. SetTimeout returns timeoutID.
TimeoutID = setTimeout(expression, msec)-Evaluates expression after msec has elapsed.

The document Object

The document object contains information about the current document and provides methods for writing information to the screen. The document object is created by using the <BODY>...</BODY> tag pair. Several of the properties reflect attributes associated with the <BODY> tag.

The anchors, forms, history, and links objects are properties of the document object. There are no event handlers for a frame. The onLoad and onUnload events are for the window object.

Properties
alinkColor-Same as the ALINK attribute.
anchors-Array of all the anchors in a document.
bgColor-Same as the BGCOLOR attribute.
cookie-Used to specify a cookie.
fgColor-Same as the TEXT attribute.
forms-An array of all the forms in a document.
lastModified-The date a document was last modified.
linkColor-Same as the LINK attribute.
links-An array of all the links in a document.
location-The complete URL of a document.
referrer-The URL of the calling document.
title-The contents of the <TITLE> tag.
vlinkColor-The VLINK attribute.
Methods
document.clear-Clears the current document.
document.close-Closes an output stream and forces data sent to layout to display.
document.open(["mimeType"])-Opens a stream to collect the output of write or writeln methods.
document.write(expression1 [,expression2], ...[,expressionN])-Writes HTML expressions to a document in the specified window.
document.writeln(expression1 [,expression2], ...[,expressionN])-Writes HTML expressions to a document in the specified window and follows them with a newline.

The anchors Object

An anchor is text in a document that can be the target of a hyperlink. It is defined by using the <A>...</A> tag pair. The anchors object has no properties, methods, or event handlers. The anchors array references each named anchor in a document. Anchors are referenced as follows:


document.anchors[index]

The anchors array has a single property, length, which stores the number of named anchors in the document. This can be referred to as follows:


document.anchors.length

The forms Object

Forms are created with the <FORM>...</FORM> tag pair. Most of the forms object properties reflect attributes of the <FORM> tag. There are also several objects that are properties of the forms object:

button
checkbox
hidden
password
radio
reset
select
submit
text
textarea

If a document contains several forms, they can be referenced by the forms array. The number of forms is found with the following:


document.forms.length

Each form can be referenced as follows:


document.forms[index]

Properties
action-The ACTION attribute.
elements-An array reflecting all the elements in a form.
encoding-The ENCTYPE attribute.
length-The number of elements on a form.
method-The METHOD attribute.
target-The TARGET attribute.
Method
formName.submit()-Submits the form named formName
Event Handler
onSubmit-Occurs when a form is submitted

The history Object

The history object is used to store information about the previous URLs visited by the user. The list of URLs is stored in chronological order. There are no event handlers associated with the history object.

Property
length-The number of entries in the history object
Methods
history.back()-Used to reference the previous URL visited; for example, the previous URL in the history list.
history.forward()-Used to reference the next URL in the history list. Until either the user or a script moves backward on the history list, this will have no effect.
history.go(delta | "location")-Used either to move forward or backward delta number of entries on the history list or to go to a specific URL on the history list referred to by location. If delta is used, the reference is backward if negative and forward if positive. If location is used, the closest URL containing location as a substring is called.

The links Object

A links object is text or a picture that is specified as a hyperlink. The properties of the links object deal primarily with the URL of the hyperlink. The links object does not have any methods.

The links array contains a list of all the links in a document. The number of links can be found using the following:


document.links.length()

A specific link can be referenced by the following array:


document.links[index]

To describe the properties of the links object, use the following fictional URL:


http://www.abc.com/chap1/page2.html#topic3

Properties
hash-The anchor name of the link, for example, topic3.
Host-The hostname:port portion of the URL (for example, www.abc.com). Note that the port is typically the default port and not shown.
Hostname-The host and domain name (for example, www.abc.com).
href-The entire URL for the link.
Pathname-The path portion of the URL (for example, /chap1/page2.html).
port-The communications port used on the host computer, typically the default port.
Protocol-The protocol being used (with the colon) (for example, http:).
Search-A search query that can be at the end of a URL for a CGI script.
Target-The same as the TARGET attribute of <LINK>.
Event Handlers
onClick-Occurs when user clicks the link.
onMouseOver-Occurs when the mouse is moved over the link.

The Math Object

The Math object is a built-in object in JavaScript. This object's properties contain many common mathematical constants and trigonometric and other mathematical functions. There are no event handlers for the Math object.

The reference to number in the methods can be either a number or an expression that evaluates to a valid number.

Properties
E-Euler's constant, approximately 2.718.
LN2-The natural logarithm of 2, approximately 0.693.
LN10-The natural logarithm of 10, approximately 2.302.
LOG2E-The base 2 logarithm of e, approximately 1.442.
LOG10E-The base 10 logarithm of e, approximately 0.434.
PI-The value of p, approximately 3.14159.
SQRT1_2-The square root of one-half, approximately 0.707.
SQRT2-The square root of 2, approximately 1.414.
Methods
Math.abs(number)-Returns the absolute value of number.
Math.acos(number)-Returns the arc cosine (in radians) of number. The value number must be between -1 and 1.
Math.asin(number)-Returns the arc sine (in radians) of number. The value number must be between -1 and 1.
Math.atan(number)-Returns the arc tan (in radians) of number.
Math.ceil(number)-Returns the lowest integer equal to or greater than number.
Math.cos(number)-Returns the cosine of number.
Math.exp(number)-Returns e numbe r, where e is Euler's constant.
Math.floor(number)-Returns the highest integer equal to or less than number.
Math.log(number)-Returns the natural log of number.
Math.max(num1, num2)-Returns the greater of num1 and num2.
Math.min(num1, num2)-Returns the lesser of num1 and num2.
Math.pow(base, exponent)-Returns the value of base to the exponent power.
Math.random()-Returns random number between 0 and 1. Note that this only works on UNIX platforms.
Math.round(number)-Returns the value of number rounded to the nearest integer.
Math.sin(number)-Returns the sine of number.
Math.sqrt(number)-Returns the square root of number.
Math.tan(number)-Returns the tangent of number.

The Date Object

The Date object is a built-in object in JavaScript. It provides many useful methods for getting and dealing with the time and date. The Date object has no properties or event handlers associated with it.

Most of the date methods have Date objects associated with them. The methods defined in this section use the Date object dateVar. The examples for many of the methods use the value stored in dateVar as follows:


dateVar = new Date("August 16, 1996 20:45:04");

Methods
dateVar.getDate()-Returns the day of the month (1-31) for dateVar (for example, 16).
dateVar.getDay()-Returns the day of the week (0=Sunday through 6=Saturday) for dateVar (for example, 5).
dateVar.getHours()-Returns the hour (0-23) for dateVar (for example, 20).
dateVar.getMinutes()-Returns the minutes (0-59) for dateVar (for example, 45).
dateVar.getMonth()-Returns the month (0-11) for dateVar (for example, 7).
dateVar.getSeconds()-Returns the seconds (0-59) for dateVar (for example, 4).
dateVar.getTime()-Returns the number of milliseconds since January 1, 1970 00:00:00.
dateVar.getTimezoneOffset()-Returns the offset in minutes of the current local time to GMT.
dateVar.getYear()-Returns the year for dateVar (for example, 96).
Date.parse(dateStr)-Parses the string datestr and returns the number of milliseconds since January 1, 1970 00:00:00.
dateVar.setDate(day)-Sets the day of the month to day for dateVar.
dateVar.setHours(hours)-Sets the hours to hours for dateVar.
dateVar.setMinutes(minutes)-Sets the minutes to minutes for dateVar.
dateVar.setMonth(month)-Sets the month to month for dateVar.
dateVar.setSeconds(seconds)-Sets the seconds to seconds for dateVar.
dateVar.setTime(value)-Sets the time to value, which represents the number of milliseconds since January 1, 1970, 00:00:00.
dateVar.setYear(year)-Sets the year to year for dateVar.
dateVar.toGMTString()-Returns a string representing dateVar as GMT.
dateVar.toLocaleString()-Returns a string representing dateVar in the current time zone.
Date.UTC(year, month, day [,hours] [,minutes] [,seconds])-Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.

The String Object

The String object is a built-in object in JavaScript and provides many string manipulation methods. The only property for the String object is the length (length).

There are no event handlers for the String object.

Methods
str.anchor(name)- Used to dynamically create an <A> tag. The name parameter is the NAME attribute of the tag.
str.big()-Creates the same effect as the <BIG> tag on the string str.
str.blink()-Creates the same effect as the <BLINK> tag on the string str.
str.bold()-Creates the same effect as the <BOLD> tag on the string str.
str.charAt(a)-Returns the ath character from str.
str.fixed()-Creates the same effect as the <TT> tag on the string str.
str.fontcolor(color)-Creates the same effect as the <FONT COLOR=color> tag.
str.fontsize(size)-Creates the same effect as the <FONTSIZE=size> tag.
str.indexOf(srchStr [,index])-Returns the offset into str of the first appearance of srchStr. The string is searched from left to right. The index parameter can be used to start the search somewhere other than the beginning of the string.
str.italics()-Creates the same effect as the <I> tag on the string str.
str.lastIndexOf(srchStr [, index])-Returns the offset into str of the last occurrence of srchStr. The string is searched from right to left. The index parameter can be used to start the search somewhere other than the end of the string.
str.link(href) -Used to create a HTML link dynamically for the string str. The href parameter is the destination URL for the link.
str.small()-Creates the same effect as the <SMALL> tag on the string str.
str.strike()-Creates the same effect as the <STRIKE> tag on the string str.
str.sub()-Creates a subscript for string str, just like the <SUB> tag.
str.substring(a, b)-Returns the substring of str indicated by the characters between the ath and bth character. The character count is from left to right starting at 0.
str.sup()-Creates a superscript for string str, just like the <SUP> tag.
str.toLowerCase()-Converts str to lowercase.
str.toUpperCase()-Converts str to uppercase.

Summary of Reserved Words

The following words are defined as part of the JavaScript language and cannot be used as variable names:

abstracteval intstatic
booleanextends interface super
breakfalse longswitch
bytefinal native synchronized
casefinally newthis
catchfloat nullthrow
charfor package throws
classfunction parseFloat transient
constgoto parseInt true
continueif private try
defaultimplements protected var
doimport public void
doublein return while
elseinstanceof short with

Summary

This chapter provides a brief introduction to the JavaScript language. In addition, it should serve as a useful reference during the development of your JavaScript applications.

While this chapter provides a concise reference to the JavaScript language, the subject is broad enough that entire books have been written about it. One useful book is Teach Yourself JavaScript in 14 Days by Sams.net Publishing.

Because JavaScript is still a new and changing language, you should also refer to Netscape's Web site for the latest information concerning the language. Netscape is located at http://www.netscape.com/.