Chapter 19

The JavaScript Language

by Bill Anderson


CONTENTS

Chapter 18, "JavaScript and the Internet," introduced the purpose and design of the JavaScript language. As mentioned previously, JavaScript is a scripting language used in HTML documents. This chapter shows you how to write JavaScript routines to make dynamic and interactive Web pages. Although LiveWire provides the compiler necessary to create server-side JavaScript applications, this chapter concentrates on using JavaScript in client-side extensions to HTML documents.

NOTE
This chapter assumes that you have a background in creating HTML documents. If you are just getting your feet wet in Internet programming, you should read Chapters 25, "HyperText Markup Language (HTML)" and 27, "Netscape Extensions," before proceeding with this chapter

This chapter takes you on a fast-paced tour of the JavaScript language. Besides requiring a background in HTML, this chapter also assumes that you have a basic background in programming.

Embedding JavaScript in HTML

There are two ways to incorporate JavaScript in an HTML document:

Using the <SCRIPT> Tag

Although Netscape Navigator treats any text bounded by the <SCRIPT> tag as JavaScript, the LANGUAGE option declares what scripting language is being used. Because there are other scripting languages for HTML, declaring the name of the scripting language used is good programming practice. Books on programming often start with a simple program that prints Hello World. Listing 19.1 shows the JavaScript version of Hello World.

NOTE
I recommend that you enter the JavaScript examples shown in this chapter and see the results


Listing 19.1. The JavaScript version of Hello World.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- Hide the script

document.write("Hello world.")

// end hiding -->

</SCRIPT>

</HEAD>

<BODY>

<BR>

This is the first script.

</BODY>

</HTML>


Listing 19.1 shows the JavaScript embedded between the <HEAD> and </HEAD> tags. If the JavaScript for Hello World were placed between the <BODY> tags, the script would give the same results as the script in Listing 19.1. Because the heading statements are read before statements in between the <BODY> tags, it is a good programming practice to place all functions and global variable definitions in the heading. By the same token, JavaScript statements related to the document should be placed in the body of the HTML document.

Not every browser processes JavaScript. To keep the HTML document from having errors in these browsers, you need to bracket the body of the script with the comment delimiters:


<!-- Hide script form non-JavaScript browser

// End of hidden text -->

TIP
Always bracket JavaScript with comment lines so that non-JavaScript browsers ignore any JavaScript statements

Handling Events

Events turn a static page into a dynamic interactive page. Events result from user actions, such as clicking a mouse button, submitting a form, or exiting a page. Netscape recognizes a certain number of events, such as those involving the use of windows or forms. Instead of discussing events at this point, the events and their related event handlers occur throughout this chapter. In Netscape Navigator 3.0, the source of events expands to include those generated in plug-ins and Java applets.

Variables and Literals

Unlike Java, JavaScript recognizes only a few types of values. They are as follows:

Although the number of data types is small, they are sufficient for the tasks that JavaScript performs. Notice that there is no distinction between integers and real numbers; both data types are just numbers. JavaScript does not provide an explicit data type for a date. However, there are related functions and a built-in date object that enable the Web page designer to manage dates.

Defining Variables

The naming rules for variables require that a variable name begins with a letter or underscore (_) and that the remaining characters are either numbers (0-9), uppercase (A-Z) or lowercase letters (a-z), or the underscore. Following are examples of legal variable names:


First_Name

t99

_name

NOTE
JavaScript does not check the spelling of variable names. Therefore, the programmer is responsible for the correct spelling of all names. When variables contain unexpected values, check to be sure that the names are spelled correctly.

The only other restriction on variable names is that they must not be the same as a JavaScript reserved word. Table 19.1 lists the JavaScript reserved words.

Table 19.1. JavaScript reserved words.

abstractextends intsuper
booleanfalse interfaceswitch
breakfinal longsynchronized
bytefinally nativethis
casefloat newthrow
catchfor nullthrows
charfunction packagetransient
classgoto privatetrue
constif protectedtry
continueimplements publicvar
defaultimport returnval
doin shortwhile
doubleinstanceof staticwith
else    

Not every word in Table 19.1 is currently used in JavaScript; some are reserved for future use. The reserved words cannot be used for variable names, function names, method names, or object names.

A variable in JavaScript accepts all valid data types. There is no way to automatically force strong typing of data. In the same script, variables can be set to different data types or even mixed data types in a single declaration. The following variable declarations are all valid:


temperature =

temperature = "The temperature is"

temperature = "The temperature is " +

Because JavaScript is loosely typed, it provides several functions for the manipulation of string and numeric values. The section "Built-In Functions" discusses the eval, parseInt, and parseFloat functions.

Scope of Variables

JavaScript supports two variable scopes:

The local variable applies only within a function and limits the scope of the variable to that function. To declare a local variable, the variable name must be preceded by var, as shown following:


var MaxValue=0

JavaScript considers any variable declaration not preceded by var as a global variable. Although JavaScript permits you to use the same variable name for local and global variables, it is not a recommended practice.

TIP
To ensure that functions inherit the correct value for a global variable, declare all global variables at the beginning of the script

Literally Literals

As opposed to variables, literals represent the fixed values used in JavaScript. JavaScript supports the following literals:

Integers can be in decimal, hexadecimal, or octal format. A decimal integer is any sequence of digits that is not prefixed by a zero (such as 4, 89, or 157). If the integer is prefixed by a zero, it is an octal value (such as 04, 065, or 0145). An integer expressed in hexadecimal format is prefixed by 0x or 0X (such as 0xff, 0X44, or 0xAE).

A floating-point literal consists of the following components: a decimal integer, a decimal point (.), a decimal fraction, and an exponent. This format allows for both fractional literals (such as 1.23 or 44.6389) or those expressed in scientific notation (3.6E-8, .4E12, or -2.7E12). Every floating-point literal must have at least one digit and a decimal point or an exponent.

Boolean literals are straightforward. Their values are either true or false.

String literals can be enclosed by either single (') or double quotes ("). The beginning and ending quote mark must be the same, as shown in the following examples:


"a double quoted literal"

'a single quoted literal'

TIP
When you write event handlers, enclose string literals in single quotes because double quotes delimit attribute values

String literals also might contain special characters to provide a limited degree of line control. Table 19.2 lists the special characters and their functions.

Table 19.2. JavaScript special characters.

Description
Special character
Backspace
\b
Form feed
\f
Newline
\n
Carriage return
\r
Tab
\t

The backslash (\) is the escape character for JavaScript. When used at the end of a line, it acts as a line continuation character. When followed by another character, it escapes that character so that the following character loses its special function. In JavaScript, the programmer uses the backslash to escape another backslash, a single quote, or a double quote.

Expressions and Operators

When literals and variables are linked by operators, the resulting statement is an expression. Examples of different types of expressions are the assignment of a literal to a variable or the computation of several literals using mathematical operators. JavaScript provides a rich variety of operators that enable programmers to write expressions ranging from the most simple to the very complex.

The JavaScript operators fall into the following categories:

JavaScript includes both binary and unary operators. A binary operator has the format


operand1 operator operand2

For example, 9 * 7 or temp = 24 are expressions with binary operators.

The unary operator has two formats:


operand operator

or


operator operand

Examples of expressions using unary operators are ++y or y++.

Assignment Operators

The assignment operator (=) is a binary operator that assigns a value to the left operand (usually a variable) based on the value of the right operand (such as FirstName = "John" or x = y * 9). For simple right-hand expressions, JavaScript prefixes the assignment operator with either an arithmetic or bitwise operator. Table 19.3 lists these shorthand assignment operators.

Table 19.3. JavaScript shorthand assignment operators.

Shorthand operatorMeaning Example
x += yx = x + Y x +=
x -= yx = x - y x -=
x *= yx = x * y x *=
x /= yx = x / y x /=
x %= yx = x % y x %=
x <<= yx = x << y x <<=
x >>= yx = x >> y x >>=
x >>>= yx = x >>> y x >>>=
x &= yx = x & y x &= 0xC0
x |= yx = x | y x |= 0x0F
x ^= yx = x ^ y x ^= 0XFF

NOTE
For those who are not familiar with C programming, be careful of the difference between the assignment operator (=) and the comparison operator (==)

Arithmetic Operators

According to the specified arithmetic operators, the purpose of arithmetic operators is to compute a single numerical value from the numerical values of either literals or variables. JavaScript supports the standard arithmetic operators of addition (+), subtraction (-), multiplication (*), and division (/). It also includes operators for modulus (%), increment (++), decrement (--), and unary negation (-).

The modulus operator (%) is a binary operator that returns the remainder of the integral division of operand1 by operand2. For example, the result of 27 % 6 is 4.

The increment unary operators add one to the operand, while the decrement unary operators subtract one from it. However, the value returned depends on the order of the operator and the operand. If the operator is prefix (++x or --x), the value returned is x+1 or x-1, accordingly. When the operator is postfix (x++ or x--), the value returned is x before it is incremented or decremented.

The other special unary arithmetic operator is the unary negation operator. It reverses the sign of the value assigned to a variable. For example, if x = -7, -x changes the value to 7.

Bitwise Operators

For those programmers who need to fiddle with bits, JavaScript provides a set of bitwise operators. For these operators, JavaScript converts the operand into a 32-bit integer before it performs the operation specified by the operator. The bitwise logical operators are

JavaScript also provides a set of bitwise shift operators that shift the bits of operand1 by the amount specified in operand2. These operands are

Logical Operators

The logical operators require that the operands are Boolean values (true or false) and they return a logical value. In the case of logical operators, the operands are expressions that evaluate to a logical value. The logical operators are

The logical NOT operator is a unary operator that reverses the Boolean value of the expression.

NOTE
JavaScript performs a short-circuit evaluation on logical operations so that false&&expr resolves to false and true||expr resolves to true. Under these cases, expr is not evaluated

Comparison Operators

The comparison operators apply to comparisons between numerical and string values and not to Boolean values. Both operands must be of the same type: numbers compared to numbers or strings compared to strings. The result of a comparison, however, is a Boolean value. The comparison operators are

JavaScript also supports the conditional expression that takes the form


(condition) ? true_value : false_value

If the condition is true, the expression has the value of true_value. Otherwise, it has the value of false_value. Like its cousins in other C-based languages, the conditional expression is like a standard expression and can be used anywhere, as shown in the following:


battery_status = (voltage > 1.3) ? "good" : "weak"

String Operators

The string operator (+) concatenates two string values and returns a string that is a union of the two values. For example, the expression


"Java" + "Script"

returns


"JavaScript"

The shorthand operator += concatenates the string in the left operand with that in the right operand and assigns the new value to the left operand.

Order of Precedence

In complex expressions involving more than one operator, the precedence of the operators determines the order of evaluation. By using parentheses, the programmer overrides these rules. Table 19.4 shows the order of precedence from lowest to highest.

Table 19.4. JavaScript operator precedence from lowest to highest.

DescriptionOperators
Assignment= += -= *= /= %= <<= >>= >>>= &= ^= |=
Conditional?:
Logical OR||
Logical AND&&
Bitwise OR|
Bitwise XOR^
Bitwise AND&
Equality== !=
Relational< <= > >=
Bitwise shift<< >> >>>
Addition/subtraction+ -
Multiply/divide* / %
Negation/increment! ~ - ++ -
Call, member() []

Control Statements and Functions

To make a page dynamic and interactive, the Web page developer needs statements that control the flow of information. Depending on computation results or input from the users, the script makes decisions that alter the path of execution. This section covers the conditional and loop statements provided in JavaScript.

Although all of the code could be written in the event handlers, this is not good programming practice. Instead, by using functions, code becomes modularized and reusable. A discussion of the function statement and a more formal discussion of comments round out this section. There are some details of the function statement that apply to objects; the next section covers these details and other control statements related to objects.

Conditional Statements

In addition to the conditional expression discussed in the previous section, JavaScript has one conditional statement-the if statement. The syntax of the conditional statement is as follows:


if (condition) {

   statements1 }

[else {

   statements2}]

The condition is any JavaScript expression that evaluates to the Boolean type, either true or false. The conditional statement is a JavaScript statement (including another if) or JavaScript expression. The following is an example of a valid if statement:


if (n>3) {

   status = true

   if (j != n) j = 0 }

else j = n

CAUTION
C programmers beware of the JavaScript rules for condition evaluation: A numerical condition evaluating to zero is not the equivalent of a Boolean true in JavaScript. Conversely, a non-zero number is not the same as a Boolean false. In JavaScript, the result of the condition must be a Boolean data type

When there is only a single statement, the braces are not necessary. For example, the following is a legal statement:


if (a==b) j=0

else j=1

Loop Statements

JavaScript supports two loop structures: the for statement and the while statement. For control within the loop structure, JavaScript provides the break and continue statements.

The for Statement

The JavaScript for statement is the same as the one for Java and C. The for statement repeats a loop until the specified condition evaluates to true or the loop is exited by a break statement. The syntax of the for statement is as follows:


for ([initial-expression;] [condition;] [increment-expression]) {

   statements

}

The order of processing for the for statement is as follows:

  1. The interpreter executes the initial-expression. This expression initializes any values needed for loop control.
  2. The interpreter then checks the condition. If it is true, control passes to the next step. If it is false, control goes to the next statement after the loop.
  3. The interpreter then executes the increment-expression, which updates the variables used for loop control.
  4. The statements then are executed and, unless a break or continue statement is encountered, control returns to step 2.

Listing 19.2 is an example of a for statement.


Listing 19.2. Example of a JavaScript for loop.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- hide script

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

   sq=i*i

   document.write("number: " + i + "square: " + sq + "<BR>")

}

// end script hiding -->

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>


The while Statement

The while statement continues to repeat the loop as long as the condition is true. The syntax for the while statement is as follows:


while (condition) {

   statements

}

The condition test occurs when the loop in the while statement is first executed and at the end of every loop. When the test returns false, control passes to the next statement after the loop. The for statement turning into a while loop is shown in Listing 19.3.


Listing 19.3. Example of a JavaScript while loop.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- hide script

i=1

while (i<=10) {

   sq=i*i

   document.write("number: " + i + "square: " + sq + "<BR>")

   i++

}

// end script hiding -->

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>


The break Statement

The break statement terminates the for or while loop and returns control to the next statement following the terminated loop. The following example illustrates how to use the break statement:


i=0

while (i<10) {

   if (i==3)

      break

   i++

}

The continue Statement

Like the break statement, the continue statement terminates the current iteration of a for or while loop; it does not exit the loop. Where it picks up the next iteration depends on the type of loop.

The following shows an example of how to use the continue statement:


i=0

while (i<10) {

   if (i==3)

      continue

   i++

}

The function Statement

A function is a group of JavaScript statements that performs a specified task. This function can then be called from any point in the document and plays an important role in writing event handlers. The format of the function statement is as follows:


function FunctionName(argument list) {

   statements

}

The Hello World script example turns into a function like the one shown in Listing 19.4.


Listing 19.4. Hello World as a function.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript"

<!-- hide the script

function DisplayIt(LineToDisplay) {

   document.write(LineToDisplay + "<BR>")

}

// end hiding -->

</SCRIPT>

</HEAD>

<BODY>

<SCRIPT LANGUAGE="JavaScript"

<!-- hide it

LineToDisplay("Hello World")

// end hiding -->

</SCRIPT>

</BODY>

</HTML>


TIP
Because the browser reads the statements bound by <HEAD>...</HEAD> first, it is good practice to initialize all global variables and define all functions in the HEAD of the document. This prevents errors from non-initialized variables and undefined functions

The arguments to a function are any JavaScript data types or objects. The array object functionName.argument[i], where functionName.arguments.length contains the total number of arguments passed to the function, references arguments by the declared variable names. This feature enables a variable number of arguments to be passed to the function as an argument array. Listing 19.5 illustrates the use of a variable argument list.


Listing 19.5. JavaScript with a variable number of arguments.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- hide it

UnorderList="UL"

function DisplayList(ListType) {            // Display Variable List

   if (ListType="OL" || ListType="UL") {    // Validate ListType

      document.write("<" + ListType + ">"      // Display type of list

      for (var i=1; i<DisplayList.arguments.length; i++)

         document.write("LI" + DisplayList.arguments[i])

      document.write("</" + ListType + ">")    // End list

      return true

   }

   else return false

}

// end hiding -->

</SCRIPT>

</HEAD>

<BODY>

<SCRIPT LANGUAGE="JavaScript"

<!-- hide it

if (DisplayList(UnorderList, "Bullet 1 text", "Bullet 2 text"))

   document.write("<P>List Display</P>")

else

   document.write("<P>Invalid List Type<p>")

// unhide it -->

</SCRIPT>

</BODY>

</HTML>


Listing 19.5 illustrates several important features of functions. A global variable is initialized in the <HEAD>. The var statement declared i to be a local variable of the function. It also shows how the return statement can be used to ensure that a function executed properly. The return statement can also return string and numerical values, as the following illustrates:


function RetExam(a, b) {

   var x=0

   x = a+b

   return x

}



TestResult=RetExam(5, 7)

Comments

JavaScript supports the two Java style formats:

The single-line comment, from C++, treats everything from the double slash to the end of the line as a comment. Thus, the following are valid examples of a single-line comment:


// this is a comment

if (a=b) c=1 // also a valid comment

The multiple-line comment follows the rules of its C equivalent and can be used to bracket any comment. The comment used to bracket the JavaScript statements, as shown in the previous examples, is an HTML comment. However, the last line of the comment needs the double slash to keep JavaScript from interpreting the line.

Fundamentals of Objects

JavaScript is an object-based language and not an object-oriented programming (OOP) language. The designers of JavaScript were not trying to create another OOP; instead, they sought to create a scripting language that provided a tool for integrating objects created with an OOP language into an HTML document. Thus, although JavaScript lacks encapsulation, inheritance, and abstraction features of C++ or Java, it has the means to access their external objects. The ability to access Java applets and plug-ins is limited in version 2.0 of Netscape Navigator, but LiveConnect and the enhanced JavaScript in version 3.0 fully support these features.

Although it lacks the Java class structure, the JavaScript class provides properties and methods for the creation objects. In addition to providing reusable objects, the object provides a means for JavaScript to implement arrays.

Objects and Their Properties

The following shows the notational system used by JavaScript to represent an object and its properties:


ObjectName.PropertyName

Without calling them objects, this chapter already used several objects and their properties: ObjectName.arguments and ObjectName.arguments.length. In addition to being referenced by name, JavaScript supports two methods of array referencing: by property name and by an index. For example, the object mydog has the following properties:


mydog.breed="small mut"

mydog.age=5

mydog.weight=25

The object also could be referenced as an array using the property name as an index:


mydog["breed"]="small mut"

mydog["age"]=5

mydog["weight"]=25

It also could be referenced as an array using the numerical index:


mydog[0]="small mut"

mydog[1]=5

mydog[2]=25

Defining Methods

A function associated with an object is referred to as a method. After defining a function in the manner described in the "Control Statements and Functions" section of this chapter, the following format associates the function with an object:


ObjectName.MethodName = function_name

The method then is referenced in the context of working with an object:


ObjectName.MethodName(parameters);

Before providing an example, I need to cover the JavaScript statements used to work with objects.

Working with Objects

The manipulation of objects requires these additional JavaScript features: for...in statement, with statement, new operator, and this keyword. Only a short description of these features is necessary, because other sections explore them in further detail.

The for...in Statement

The for...in statement provides a loop mechanism for iteration through all of the properties of an object. Its format is as follows:


for (variable in Objectname) {

   statements

}

The following example uses this statement to list the properties in an object and their associated values:


function ListProperties(obj, obj_name) {

   var result = ""

   for (var i in obj) {

      result += obj_name + "." + i " = " + obj[i] + "<BR>"

   }

   return result

PropList = ListProperties(mydog, "mydog")

In the preceding example, the variable i is the name of the property. The example then indexes the object using the property name-obj[i].

The with Statement

In some situations the same object is referenced several times. The with statement establishes a default object for a bracketed set of statements. Its format is as follows:


with (ObjectName) {

   statements

i

The Math object provides an example of how to use the with statement:


var r =

var x =

with (Math) {

   r = p / (1 - cos(a))

   x = (2 * p * cos(a)) / (sin(a) * sin(a))

}

The new Operand

For a user-defined object type, the new operand provides a means of creating a new instance of that object type. The syntax of this operand is as follows:


ObjectName = new ObjectType(param1 [, param2,] É [, paramN])

The section "Creating New Objects" contains examples of the use of this operand.

The this Keyword

this refers to the current object. As the next section shows, it plays an important role in the writing of functions and methods.

Creating New Objects

Although JavaScript contains a large number of predefined objects, the developer can create additional user-defined objects. The creation of objects requires the developer to perform two steps:

  1. Define the object type by writing a function.
  2. Create instances of the object using the new operand.

The function defines the object type, the properties, and the methods. For example, to create an object type for dogs, the following function needs to be written:


function dog(breed, age, weight) {

   this.breed = breed;

   this.age = age;

   this.weight = weight;

}

In the preceding example, the this keyword refers to the instance of the object being created. It is important to note that the assignment of values to a property requires that the statement end with a semicolon.

Using this function, the new operand defines a new instance of the object. For example,


mydog = new dog("small mut", 5, 25);

In addition to the regular JavaScript data types (string, numeric, and Boolean), another object can be the property of an object. For example, to add a license number to the object type for a dog, the license number also could refer to another object.


function doglicense(owner, phone_number) {

   this.owner = owner;

   this.phone_number = phone.number;

}



AZ123 = new doglicense("John Smith", "999-9999");

The object type then needs to be modified to include the new information:


function dog(breed, age, weight, license) {

   this.breed = breed;

   this.age = age;

   this.weight = weight;

   this.license = license;

}



mydog = new dog("mixed mut", 5, 25, AZ123);

To reference the owner of mydog, the syntax would be


mydog.license.owner

NOTE
If a new property is added to an object without changing the object type, the additional property only affects that object and not all other instances of the object type

NOTE
A string variable or a string literal is a string object. String methods are associated with these objects, as discussed in the section "Built-In Objects and Functions.

Defining Arrays

Unlike other languages, JavaScript lacks an array data type. However, an equivalent function is performed by creating an object that emulates an array. The first step is to define an array object type:


function MakeArray(n) {

   this.length = n;

   for (var i = 1; i <= n; i++)

      this[i] = 0;

   return this

}

The next step is to define an instance of the MakeArray object type:


ExmpArray = new MakeArray(20);

When you assign values to array elements, it looks like assigning values to an array data type. The difference is that the array begins with one and not zero, because zero defines the length of the array:


ExmpArray[1] = "test1"

ExmpArrya[2] = "another test"

Built-In Objects and Functions

The objects and functions described in this section are part of the JavaScript environment and, therefore, they are browser independent. These objects and functions are as follows:

Taken as a whole, these objects and their associated methods provide a powerful set of additions to the programmer's toolbox. The string and date objects extend the basic set of data types to cover most development needs. The Math object provides all the standard functions for performing complex mathematical routines.

The String Object

Whether a quoted string is a string variable or a string property of an object, it is a string object; everything placed between quotes is a string object. There are two ways to use a string object:

  1. stringName.propertyName
  2. stringName.methodName(parameters)

String Object Properties

The string object has only one property-length. Because it is a property, the following are all valid references:


StringLength = stringVariable.length;

StringLength = mydog.name.length;

StringLength = "This is a string".length;

String Object Methods

A large number of methods is associated with the string object. Besides the normal string manipulation functions, many of these objects wrap the string with HTML tags. The following is a list of the string object methods:


document.write("Other Links".anchor("other_links"));

The Math Object

The Math object provides a set of standard mathematical values and methods that augment the set of mathematical operators provided with JavaScript. As opposed to other objects, the Math object does not require an instance of the object before using the math methods. To simplify the entering of names and to make the script more readable, the Math methods often are bounded by the with statement. The syntax for the Math object is as follows:

  1. Math.propertyName
  2. Math.methodName(parameters)

The Math Object Properties

The Math object provides eight properties. These properties define various mathematical constants. Table 19.5 describes the properties and gives their approximate values.

Table 19.5. The Math object properties and their values.

PropertyDescription Approx. value
EEuler's constant 2.718
LN2Natural logarithm of 2 0.693
LN10Natural logarithm of 10 2.302
LOG2EBase 2 logarithm of e 1.442
LOG10EBase 10 logarithm of e 0.434
PIRatio of circumference to diameter 3.14159
SQRT1_2Square root of one-half 0.707
SQRT2Square root of two 1.414

Math Object Methods

The Math object provides a number of Math methods that augment the set of mathematical operators:

The Date Object

Although JavaScript does not provide a Date data type, it provides a Date object that allows the handling of date and time information. One caveat is that all dates are in milliseconds from January 1, 1970, 00:00:00. Due to the way JavaScript handles dates, dates before 1970 are invalid dates.

The Date object requires that an instance of the Date object exist prior to the use of its methods. The instance can either be a new object or the property of an existing object. There are four ways to define the new instance:


dateObjectName = new Date()

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

dateObjectName=new Date(year, month, day)

dateObjectName=new Date(year, month, date, hours, minutes, seconds)

Format one sets the date and time to the current date and time. Leaving out the time sets the value to zero. Because the Date object does not contain any properties, there is only one format for the Date methods:


dateObjectName.methodName(parameters)

The exceptions are UTC and parse methods, which are static methods and use


Date.UTC(parameters)

Date.parse(parameters)

Table 19.6 describes the values returned by the various get commands.

Table 19.6. Extracting information from the Date object.

Date methodReturned value
getDate()Day of the month
getDay()Day of the week
getHoursHour of the day
getMinutesMinutes in the hour
getMonthThe month
getSecondsSeconds in the minute
getTimeMilliseconds since 1/1/1970
getTimezoneOffsetOffset between local time and GMT
getYearThe year

Besides being able to retrieve information on the Date object, the methods in Table 19.7 show how to change date information.

Table 19.7. Setting information into the Date object.

Date method
Valid values
setDate(dayValue)
1-31
setHours(hoursValue)
0-23
setMinutes(minutesValue)
0-59
setMonth(monthValue)
0-11
setSeconds(secondsValue)
0-59
setTime(timeValue)
>=0
setYear(yearValue)
>=1970

Two additional methods are used to convert the date to a string value. They are as follows:

The Date object also provides two static methods for handling strings; it has the format of Date.method(). These methods are as follows:

Built-In Functions

JavaScript supports several built-in functions that are not related to any object. These built-in functions are as follows:


var x =

var y =

var z = "if (x <= 9) (x*y) else (x/y);"

document.write(eval("x + y / 4"), "<BR>")

document.write(eval(z), "<BR>")

Netscape Objects

In addition to the JavaScript objects and methods, the Web page developer has access to the objects and methods in the Netscape browser. This section reviews the Netscape Navigator objects and methods. The next section looks at how to use the objects and methods in the management of windows and frames.

The Navigator Object Hierarchy

Netscape Navigator builds an instance hierarchy that reflects the document being processed. As an instance hierarchy, there are no classes as defined in Java. However, the instance hierarchy works with the JavaScript approach to objects. Figure 19.1 shows the structure of the Navigator object hierarchy.

Figure 19.1 : The Netscape Navigator object hierarchy.

This hierarchy is important for creating references to objects and their properties. The children of an object are properties of the parent object. Because all objects are descendants of the window object, the window object itself is not referenced when referencing any object or property within the current window. For example, the reference to the instance of myform is document.myform. However, referencing a document in another window requires the addition of the window name to the object reference.

The Importance of HTML Layout

The proper use of JavaScript depends on having a basic understanding of how Netscape Navigator processes an HTML document. When an HTML document is loaded, the browser starts processing at the first line of the document. The browser lays out the screen in the order of the HTML statements in the document. After the screen is drawn, it cannot be redrawn without processing a new document. How this affects frames and windows is the topic of the next section.

The corollary to this is that an instance of an object exists only after encountering the HTML that generates the instance. Thus, JavaScript cannot reference an HTML object, such as a form, or execute a function until the browser processes the statement. For example, JavaScript cannot reference a form object until the browser processes the HTML for the form. Similarly, the changing of a property after the browser used the property in the layout of the window does not affect its value or appearance.

Although the constraints seem onerous, understanding the behavior of processing HTML and JavaScript saves a lot of frustration. The key principle to remember is that an HTML document is sequentially processed and JavaScript is part of that sequential process.

The Window Object

The window object is the parent of all objects. It includes the properties that define all windows and frames within a window. When the browser initially loads the HTML document, it starts with a single instance of a window object. If the HTML document creates frames, the frame information is stored in a frame array object. By the same token, opening a new window creates a child window object. The power of JavaScript lies in its capability to utilize the properties and methods of the window object.

The section "Windows and Frames" goes into more detail about the window object itself. This section covers the objects that are properties of the window object. These objects are the

Of the three, the document is the most important object in the hierarchy. The document object itself contains properties that refer to other objects. The most important of these are the following:

The upcoming sections cover each of these objects. However, they cover only those objects, properties, and methods that are related to JavaScript.

The location Object

The location object contains information about the current URL. The reference to the object is as follows:


[windowReference.]location[.propertyName]

The properties of the location object refer to the individual parts of the URL:


protocol//hostname:port pathname search hash

NOTE
The location object and the location property of the document object (document.location) have different purposes. The location object can be changed, but the location property cannot be changed

The properties of the location object are as follows:

NOTE
Although JavaScript permits the modification of the individual properties, sound programming practice calls for changing the href property. This approach prevents any errors resulting from the browser attempting to access the URL before all changes are made

The History Object

Access to the History object is a controversial subject because it enables the script to send the history back to the server. To prevent this from being misused, Netscape Navigator versions 2.01 and above no longer enable access to this object.

The document Object

The document object holds the properties, objects, and methods that define the presentation of the document. It refers to that part of the HTML document defined by the <BODY></BODY> tags. The following subsections discuss the components of the document object, except for the form object (which is covered in the "The Form Object" section, later in this chapter).

The document Object Properties

The HTML options to the <BODY> tag define the document object properties. JavaScript references all of these properties, except for the background image.

NOTE
The string required to change the color properties is in the format of document.colorProperty = "#RRGGBB" or document.colorproperty="colorName". Any color property defined in the <HEAD></HEAD> tags takes precedence over the <BODY> tag option. The outcome of color changes made in the <BODY> depends on the color property

The color document object properties are as follows:

The document object also contains the following non-color related properties:

The anchors Object

The anchors object contains an array of all anchors declared by the NAME attribute of the <A> </A> tags. The array begins at 0 and continues through document.anchors.length - 1. The value of document.anchors[index] is null.

TIP
Before using it to set a value such as location.hash, it is possible to check the validity of the anchor by comparing it to the array length; you use sequential numbers to identify anchors

The link Object

The link array contains the link objects defined by the <A></A> tags or the link method. The array includes objects for both the HREF and NAME attributes. With the addition of the TARGET attribute, the properties of each link object are identical to those of the location object.

NOTE
The link array is a read-only array. Additional entries are added via the <A></A> tags. The link method modifies existing entries in the link array

The link object provides two event handlers: onClick and onMouseOver. The section called "The Form Object," later in this chapter, describes how to use these event handlers.

The cookie Property

The cookie property contains a string value of the cookie entry from the cookies.txt file for the document. For a complete description of how to use cookies, see the Netscape cookie specification. The substring, charAt, indexOf, and lastIndexOf string methods can be used to dissect the cookie string. Chapter 18 contains an example of how to read the cookie string.

The document Object Methods

The document object contains five methods:

As shown in previous examples, the document.write method, without a window reference, writes text to the current window. The document.writeln() method is the same as document.write, except that it inserts a newline character at the end of the argument. The format for these methods is as follows:


document.write(expression [, expression2] ... [expressionN])

document.writeln(expression [, expression2] ... [expressionN])

The default MIME type is text/html. However, the document.open(["mimetype"]) method enables the opening of other MIME types, such as text/plain, image/gif, image/jpeg, image/x-bitmap, and plugIn. The document.open() method opens a stream to collect the output of the write and write.ln methods. If the MIME type is text or image, the browser opens a stream for layout; for plugIn, the browser opens it to a plug-in. If a document already exists in the target window, the open method clears it.

NOTE
Currently, it is not possible to print any text generated by JavaScript via the write or the writeln methods

The stream stays open until the browser encounters a document.close() method. The document.close() forces the content of the stream to display. The document.clear() method clears the content of the window.

The Form Object

The HTML <FORM></FORM> tags provide the means for user input of data, and output of variable data to the user. The user input might affect choices for client-side use, or it can be sent to the server. On the other hand, variable data such as marquees can be displayed on the form. On the input side, event handlers provide a means to invoke JavaScript routines to perform such tasks as editing data. On the output side, JavaScript plays a bigger role in the managing of data to be displayed in the form.

This section discusses the form object and its properties. Due to the length of forms examples, this section only presents snippets of code. The next chapter gives full-blown scripts illustrating the use of forms and event handlers.

Event Handlers

Event handlers constitute one of the major uses of JavaScript. Events are the result of user actions, such as the clicking of a mouse button, the checking of a box, or the submission of a form. Event handlers are defined in the HTML tags along with the JavaScript related to the event. The following example illustrates the coding of an event handler:


<INPUT TYPE="button" VALUE="Submit" onClick="validate(this.form)">

In the preceding example, the keyword this refers to the current object, which is the button object. By stating this.form, the reference is made to the form object containing the button. While the preceding example executes a function, JavaScript statements also are valid. When there is more than one statement, each statement must be separated by a semicolon.

TIP
Good programming practice calls for the use of functions because they make code easier to read and can be reused

NOTE
Until an HTML document is loaded into a window that contains the <BODY></BODY> tags, a window contains no event handlers

The following is a list of event handlers supported by JavaScript:

The event handlers are a part of various objects. Some objects support more than one event handler, and some event handlers appear in multiple objects. Table 19.8 shows the relationship between event handlers and objects.

Table 19.8. The relationship between event handlers and objects.

ObjectEvent handlers
buttononClick
checkboxonClick
formonSubmit
linkonClick, onMouseOver
radioonClick
resetonClick
selectonBlur, onChange, onFocus
submitonClick
textonBlur, onChange, onFocus, onSelect
textareaonBlur, onChange, onFocus, onSelect
windowonLoad, onUnload

The forms Array

The forms array contains an entry for each form object created by the <FORM></FORM> tags. For JavaScript, it is a read-only array composed of the following properties:

The following are the valid means of addressing the form objects:


formName.propertyName

formName.methodName(parameters)

forms[index].propertyName

forms[index].methodName(parameters)

Form Object Methods

The form object has only one method-submit. The submit method performs the same action as the submit button of an HTML form and has the following syntax:


document.formName.submit()

The element Objects

The element objects reflect the element entries in the <FORM></FORM> tags. Table 19.9 lists the element objects and their properties.

Table 19.9. The properties of element objects.

Element objectProperties
buttonname, value
checkboxname, value, checked, defaultChecked
hiddenname, value
passwordname, value, defaultValue
radioname, value, checked, defaultChecked, length
resetname, value
selectname, length, options array, selectedIndex
submitname, value
textname, value, defaultValue
textareaname, value, defaultValue

The properties are addressed as document.elementName.property, or as document.formName. elements[index].propertyName, where elementName is the value of the name property for the element object.

The element Methods

The element methods emulate their cousins, the event handlers. However, there are some caveats, as the following shows:

Except for the radio object, the methods are addressed as document.elementName.methodname(). Table 19.10 lists the element objects and their corresponding methods.

Table 19.10. The methods of element objects.

Element objectMethods
buttonclick
checkboxclick
hidden(has no methods)
passwordblur, focus, select
radioclick
resetclick
selectblur, focus
submitclick
textblur, focus, select
textareablur, focus, select

Windows and Frames

Windows and frames create more confusion for Web page developers than any other aspect of the browser. When Netscape Navigator starts, it opens a window and, depending on how the options are set, loads a document into the window. If you select the menu option File | New Web Browser, a new window is opened. In this case, closing the original window does not close the new window.

On the other hand, frames are created according to the <FRAMESET></FRAMESET> tags in the HTML document. It subdivides the screen's real estate into a number of frames. When the document that defined the frames is closed, the frames go away because their existence depends on the document.

Chapter 18 provides examples that illustrate the difference in behavior between windows and frames, even though both are containers for documents. This section concerns itself with the properties and methods of the window and frame objects.

The Window Object Properties

One of the major features of JavaScript is its capability to create and manipulate windows. These windows are not limited to just displaying messages; depending on the parameters set, they can be another instance of the browser. The following properties of the window object reflect the flexibility of the browser window:

The forms for referencing window properties are


window.propertyName

self.propertyName

top.propertyName

parent.propertyName

windowVar.propertyName

propertyName

The Window Object Methods

The following are the window or frame object methods:


toolbar=yes|no

location=yes|no

directories=yes|no

status=yes|no

menubar=yes|no

scrollbars=yes|no

resizable=yes|no

width=pixels

height=pixels

NOTE
After it is created, the window is independent of the parent window; if the parent window closes, the window created remains open. The onUnLoad event handler closes the windows created

The preceding methods are referenced as follows:


window.methodName(parameters)

self.methodName(parameters)

top.methodName(parameters)

parent.methodName(parameters)

windowVar.methodName(parameters)

methodName(parameters)

CAUTION
The open() and close() methods need to be referenced as window.open() and window.close() to avoid any conflicts of scope with document.open() and document.close()

Dividing the Window into Frames

Frames divide a window into multiple, independently scrollable frames on a single screen. Frames are created via the <FRAMESET></FRAMESET> tags in an HTML document. Each document creates a frame array for that document. If a document opened in one of the frames contains a <FRAMESET> tag, that frame is divided into frames by that document. This hierarchy of framesets is important in referencing the properties and methods of frames.

NOTE
Frames have all the properties of a window. The entire hierarchy for the frame structure is the same as the window structure. (Refer to Figure 19.1.

The structure under any window or frame can be referenced. Thus, object properties in one window or frame can change object properties in another window or frame using the structure shown in Figure 19.1.

NOTE
The HTML document that uses <FRAMESET></FRAMESET> contains only frame statements. After the frames are opened, the original document is no longer visible. The HTML document is one frame that can control the other frames. Thus, the possibilities for screen management give the Web page developer tremendous freedom in the development of interactive Web documents

Summary

JavaScript is more than a simple scripting language and less than a full-blown, object-oriented programming language. It is the glue that binds many diverse elements into a single dynamic and interactive environment.

This chapter presented the fundamentals of JavaScript and described the objects and their properties that are available to JavaScript. This chapter dealt with the pieces to the puzzle, and Chap-ter 18 puts the pieces together to illustrate the uses of JavaScript.