- Special Edition Using Java, 2nd Edition -

Chapter 55

Starting with JavaScript


by Andrew Wooldridge

By now you have read a lot about the newest version of Java, and in the previous chapter, I began to talk about one of Java's partners in Web development—JavaScript. You may be wondering (if you jumped straight to this chapter or are reading this in the bookstore,) why there is a chapter on JavaScript in a book about Java. The reason is quite simple. JavaScript complements Java's capabilities in the Web browser environment. It allows people with little or no programming experience who are daunted by Java's complexity to create interactive and Web-based applications.

This chapter gives you an overview of the JavaScript language and shows you how you can use JavaScript to enhance your Web pages.

The Basics

JavaScript is a scripting language that is loosely based on Java. By imbedding JavaScript code in an HTML document, you can have greater control of your user's experience as well as pass a larger amount of computation (originally only available via CGI scripts) down to the client-side browser. These scripts are read sequentially by the browser as it is loading a page and can execute commands immediately—which may affect the page even before it completes loading.

Because JavaScript lives inside your HTML document, it can either exist as a complete script that is embedded in the <head> or <body> elements, or it can consist of event handlers that are written directly into the HTML code.

See “Event Handlers,” Chapter 55 for more information.
 

In listing 55.1, you can see how to build the “skeleton” of a JavaScript script in a document via the <script> tag.

Listing 55.1 The script tag.

<SCRIPT LANGUAGE="JavaScript">
<!-- HTML comment tags to hide script from old browsers
[JavaScript statements...]
// End hiding the code from old browsers -->
</SCRIPT>

You can see from this example that the <script> tag is somewhat similar to the <applet> tag you use when you embed Java code. The SCRIPT tag has an attribute called LANGUAGE that allows you to specify in which language the browser needs to interpret the following code. This makes the <script> tag versatile, in that you may eventually use it to embed Visual Basic Script, TCL, Perl, and more scripts.

Another attribute to the <script> tag is SRC. Implemented in Netscape 3.0), the SRC attribute allows you to write all of your script in another file and reference that file—instead of having to paste all of the statements in the HTML. If you use the SRC tag, anything you place between the <script>...</script> is ignored. Thus, you can place alternative HTML for non-JavaScript enabled browsers. Listing 55.2 uses the SRC attribute.

Listing 55.2 JavaScript with SRC.

<SCRIPT LANGUAGE="JavaScript" SRC="footer.js">
You must not have a JavaScript Enabled Browser if
you see this (poor you!) Click <A HREF="foo.html">here</A>
to go to another page.
</SCRIPT>

In listing 55.2, the browser would load the script contained within FOOTER.JS as if it had been typed in the HTML document instead.

Your First Script

When you start learning about JavaScript, you will find it very useful to begin with the basics, immediately start up your Web browser (Netscape 2.0+ and Microsoft Internet Explorer 3.0+), and test out what you learn.

Let's begin with a simple script and explain what will happen when you load this page. Listing 55.3 is an example of the typical “Hello World” program that is very popular for testing out new languages. In this example, you are essentially telling the browser to display the string “Hello World!” as if you had directly typed that string in your HTML document. (Note that I usually capitalize my HTML or JavaScript tags. This is simply a programming convention, but it makes the code easier to read.)

Listing 55.3 "Hello World!" implemented in JavaScript.

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide me from old browsers
document.write("Hello World!");
// End Hiding -->
</SCRIPT>
</HEAD>
<BODY>
Are you ready for JavaScript?
</BODY>
</HTML>

Try this one out on your browser and see the results.

Basically, the browser reads this code into the JavaScript interpreter. The text string "Hello World!" is passed to the write function of the document object which in turn instructs the browser to display the phrase "Hello World!" on a new page. Notice that the actual code is not displayed in the browser window. This is because the HTML parser never received this code, as it was passed to the JavaScript interpreter once the HTML parser encountered the <SCRIPT> tag.

Events

Most of the time, you will be building scripts that do such things as store information, display data in a certain format, perform some calculations, or respond to user actions (called events). JavaScript has all of the elements that make up a powerful scripting language and can handle all of these tasks. One of the primary tasks JavaScript is used for is intercepting and handling events. Just about any way you respond to your browser can be intercepted by JavaScript. Furthermore, your response can trigger other events, or functions.

Essentially, functions are stored chunks of code that are executed at some interval—either immediately, when the document is loaded, or in response to some triggered event. Think of functions as collections of instructions that allow you to pull out some behavior you might want to perform over and over again or possibly reuse.

When JavaScript encounters an event, it passes it to an event handler. Event handlers are tags that point to the specific functions to be executed. Table 55.1 lists the events and handlers in JavaScript.

Table 55.1 Events and Event Handlers in JavaScript

Event Event Handler To Trigger Event
blur onBlur In a form element, user clicks (tabs) away from element.
click onClick In a form element or link, user clicks element.
change onChange In a form text, text area, or select object, user changes value.
focus onFocus In a form element, clicks (tabs) to element.
load onLoad Happens when page is loaded.
mouseover onMouseOver Happens when mouse is passed over links or anchors.
select onSelect In a form, user selects input field.
submit onSubmit In a form, user submits a form (clicks the Submit button).
unload onUnload User leaves the page.

Using Event Handlers

Although you can use event handlers anywhere in your JavaScript scripts, you will usually place them either inside HTML form elements or alongside anchors or links. The reason for this is that JavaScript uses the HTML form as a way to send data to your JavaScript script or perform some “preprocessing” on the data, not just to send data back to the server.

For example, an enrollment form on your site asks the users a number of questions about themselves, and you want to make sure they at least fill out their names and ages. Before JavaScript, the form would be submitted directly back to the Web server, which would check that the appropriate fields were filled out. Then, if they weren’t, the form would be sent back to the users, asking for the appropriate information. Now, JavaScript can check this field before it is sent and ask the users to fill out that information, without all the overhead of reconnecting to the remote server.

Let's look at an example of how you might add an event handler to your existing HTML code. Most of the time, you will follow this general syntax:

<TAG eventHandler="JavaScript code">

Of course, TAG is some HTML tag, and eventHandler is any one of the event handlers you saw in table 55.1. The “JavaScript code” can be any valid JavaScript code but is usually a call to a function that you loaded earlier in the document. Listing 55.4 demonstrates an embedded JavaScript event handler in a common hypertext link. When you click the link, a dialog box displays the text, followed by an OK button for you to click to return to the page.

Listing 55.4 An event handler in an HREF.

<A HREF="#" onClick="alert('Wow! It Works!');">Click here for a message!</A>

There is a lot to notice in this example:

Now that you have seen the two main ways you can implement JavaScript in your HTML code (either in scripts contained by the <SCRIPT>...</SCRIPT> tags or directly embedded in HTML form elements and links), let's look at the building blocks of JavaScript code.

Variables

To create a variable in JavaScript, you simply declare it using the keyword var. You can initialize this variable with some value when you declare it, but it is not required. Listing 55.5 shows some examples of variables created in JavaScript.

Listing 55.5 Variable declaration in JavaScript.

var foo = 23
var a, b, c = "letter"
var aNumber = "99"
var isItTrue = false
var flag1 = false , bingo = null , star

JavaScript is relatively unique in respect to the fact that you cannot explicitly set a type to a variable, such as casting a string to an integer, like you would in Java. Types are found in JavaScript, but they are set implicitly. This means that the type a variable has is defined by the context in which it is either defined or used.

When you initialize a variable with a string value (as variables a, b, and c in listing 55.5), it is a string type; if you initialize it with a number, it becomes an integer type value (as in variable foo in listing 55.5). When you place a number of variables within a single statement, such as

foo + bar + baz

attempts to treat all of the variables as having the same type as the first variable. If foo was a string and bar and baz were originally integers, JavaScript would treat bar and baz as if they were strings. The implicit nature of JavaScript variables allows you to reuse variables easily without worrying about their type.

If you set some variable day to “Tuesday” and later in the script decide to assign 46 to day, the JavaScript interpreter (inside the browser) will not complain. Because of this, however, you should be careful when naming your variables so that they do not overlap in scope and cause strange errors in your scripts. You will find it extremely helpful to experiment with declaring and setting variables from the interpreter window I talked about earlier. (In Netscape, just type javascript: in the open URL window.

See “Interpreted Versus Compiled,” Chapter 54 for more information.
 

Table 55.2 contains a list of the possible implicit data types in JavaScript, along with their possible values:

Table 55.2 Data Types in JavaScript

Data Type Values
Number 100, -99.99, 0.000001
Boolean true, false
Strings “this is a string”, “This is another”, “5555”
Null A special keyword with a null value

Variable Names

JavaScript follows the same naming rules for creating variable names as Java. Your variable must start with a letter or an underscore and can contain subsequent numbers, letters, or underscores. Listing 55.6 gives you a sampling of possible variable names in JavaScript. Remember to keep your names unique and that in JavaScript, names are case-sensitive.

Listing 55.6 Variable name examples.

Too_hot
cold999
_100JustRight
This_is_a_long_variable_name_but_it_is_valid000

Variable Scope

Earlier, I mentioned that you will want to keep your variable names distinct from one another in order to prevent overwriting values, but what if you really want to use the same name? This is where variable scope comes into play. Global variables are accessible by your entire script and all of its functions. Local variables are accessible only to the function from which it was created. Those variables are destroyed when that function is complete. To define a variable as a global variable, simply assign a value to it (such as “foo = 95”).

To define a local variable inside a function, use the var keyword.

Literals

You can think of a literal as the value on the right-hand side of an equality expression. It is the concrete way to express values in JavaScript and is very similar to Java's method. Here is a list of literals and their possible values:

(77, 56565565)

08988

Strings can contain special characters that affect how they are eventually displayed:

Expressions and Operators

Having values is not enough for a language to be useful. You must have some way to manipulate these values meaningfully. JavaScript uses expressions to manipulate numbers, strings, and so on. An expression is a set of literals, operators, subexpressions, and variables that evaluate to value. You can use expressions to assign a value to a variable, as in

today = “Friday”

or an expression can simply evaluate to a value, as in

45 - 66

JavaScript uses arithmetical expressions (that evaluate to some number), string expressions that evaluate to another string, and logical expressions that evaluate to true or false. Operators behave very similarly to their cousins in Java. Table 55.3 summarizes the various operators that are available in JavaScript.

Table 55.3 JavaScript Operators

Operator Explanation

Computational

+ Numerical addition and string concatenation
- Numerical subtraction and unary negation
* Multiplication
/ Division
% Modulus (remainder)
++ Increment (pre and post)
-- Decrement (pre and post)

Logical

==, !== Equality and inequality (not assignment)
< Less than
<= Less than or equal to
> Greater than
=> Greater than or equal to
! Logical negation (NOT)
&& Logical AND
|| Logical OR
? Trinary conditional selection
, Logical concatenation

Bitwise

& Bitwise AND
| Bitwise OR
[af] Bitwise excluse OR (XOR)
~ Bitwise NOT
<< Left shift
>> Right shift
>>> Unsigned right shift

Assignment

= Assignment
X= Aggregate assignment (where X can be +, -, *,/,%, &, [af], <<, >>, |, >>>) Example: ( A += B is equivalent to A = A + B)

The operator precedence is identical to Java's. JavaScript uses lazy evaluation going from left to right. If, while evaluating an expression, it encounters a situation where the expression must be false, it does not evaluate the rest of the expression and returns false. If you want to group expressions to be evaluated first, use the parentheses, for example:

(56 * 99) + (99 - (44 / 5))

A handy expression is the conditional expression. Very underused, this expression allows you to evaluate some condition quickly and return one of two values. Its syntax is:

If the condition is true, then the first value is returned; otherwise, the second is returned. For example:

Control Statements

Now that you have assignment and mathematical operators, you can assign values to variables, perform simple math expressions, and so on. But you still don't have the ability to write any kind of meaningful JavaScript code. You need to have some way of controlling the flow of statement evaluation, to make decisions based on values, to ignore some statements, and to loop through a series of statements until some condition is met.

This is where control statements come into play. JavaScript groups these statements into conditional (if...else), loop (for, while, break, continue), object manipulation (for...in, new, this, with), and comments (//, /*...*/). Examples of each of these statements are explored in this section. (Note that I come back to the object manipulation statements later, after you learn about JavaScript's object model.)

JavaScript uses brackets to enclose a series of statements into a complete chunk of code. When JavaScript encounters these chunks, all of the statements within are evaluated (unless, of course, JavaScript encounters another branch beforehand, as you learn soon).

Conditional Statements

These are statements that allow your script to make decisions based on criteria you select.

if...else

When you want to execute some block of code based on some other condition, you can use the if statement. Its syntax is:

if ( someExpressionIsTrue) {
zero or more statements...
}

If you want to either execute some block of code or another, you can use the if...else statement, which forces the execution of one block or the other. Its syntax is:

if ( someExpressionIsTrue) {
some statements...
}
else {
some other statements...
}

If you want to execute just one line of code, you can omit the brackets. This is not recommended, however, because your code will not be as easy to follow later.
 

Listing 55.7 shows how you might implement an if...else statement. It also shows you how you can chain together multiple else and if statements.

Listing 55.7 If...else statement chaining.

if...else statement
if ( jobs < 100) && (money <= budget) {
poor = true;
free = (99 - x) / jobs ;
}
else if (jobs != overTime) {
workers = "Strike"
}
else {
poor = false;
workers = "Happy";
}

In a moment, I talk about functions and how they are constructed in JavaScript (refer to the section “Functions in JavaScript” later in this chapter). For now, let's start with a working definition of a function as some set of instructions that performs an action or returns a value. Because a function can return a value, it can return a boolean true or false. Furthermore, you can use a function call in an if statement as the test. Listing 55.8 shows how you might implement this.

Listing 55.8 Using a function as a conditional.

if ( pageIsLoaded) {
alert ("All Done!");
done = true;
}
else {
done = false;
}

Loop Statements

Sometimes you want to execute a series of statements over and over again until some condition is met. An example of this might be to play a sound in the background of your page until the user clicks “Stop!” or to repeatedly divide some number by 6 until it is less than 50. This action is performed in JavaScript by the for and the while structures.

for

A for loop repeats some series of statements until some condition is met. The for loop structure is virtually identical to the structure in Java. Its syntax is:

for ([some initial expression] ; [condition] ; [increment expression] ) {
some expressions...
}

You build a for loop by setting up three expressions that follow a more or less standard format. The initial expression can be of any degree of complexity, but it usually is simply an initial assignment of value to the counter variable. In the second expression, the condition is executed once for each pass through the expressions. If the expression evaluates to true, then the block of expressions is executed. If the expression evaluates to false, the for loop is completed and the interpreter jumps down the next expression after the loop. The increment expression is evaluated after each pass through the loop and is usually where the “counter” variable is incremented or decremented. Essentially what this means to you is that you initialize some counter, test some condition, execute the enclosed statements if true, increment the counter, test the condition again, and so on.

Although not required, you should use the increment expression to change some value that will eventually render the condition expression false. Otherwise, your for loop will run forever (or until you get tired of waiting and reboot your computer).
 

Listing 55.9 gives you a simple example of a for loop in JavaScript.

Listing 55.9 An example of a for loop.

<script language="JavaScript">
var myMessage = "Here we go again! <br>";
var numberOfRepeats = 100;
for ( i=0; i < numberOfRepeats ; i++) {
document.write(myMessage);
}
</script>

while

The while loop is a simpler version of the for loop, in that it just tests some expression each time around and escapes if that expression is false. You will probably use while loops when the variable you are testing for is also present inside the statement block that you are executing during each loop. Note that the condition is tested first before the statements are executed, and that the condition is tested only once for each loop. Here is the standard syntax for a while loop:

while (somecondition) {
some statements;
}

Listing 55.10 will repeatedly display a series of lines that state the current value of tt until tt is greater than or equal to xx—which in this case is 55.

Listing 55.10 Listing An example of a while loop.

<script language="JavaScript">

tt = 0
xx = 55
while ( tt <= 55) {
tt += 1;
document.write ("The value of tt is " + tt +". <br> ");
}
</script>

break and continue

Sometimes you might want to have a finer degree of control over your block of statements within a for or while loop. Occasionally, you might want to arbitrarily “jump” out of a loop and continue down to the next statement. Or, you might want to stop the execution of statements in the current loop and start a new loop. You can achieve both of these options by using break and continue. break causes the for or while loop to terminate prematurely and the execution to jump down to the next line after the loop. continue stops the current loop and begin a new one.

It is easy to get these statements confused, and their purpose may become unclear over time. An easy way to remember how these work is to think of break as breaking the loop, which renders the loop inoperable. Then, the program continues down. You can think of continue as a way of skipping whatever is below it and starting again. Listings 55.11 and 55.12 mirror 55.9 and 55.10 and illustrate these control statements.
 

Listing 55.11 Breaking out of a for loop.

<script language="JavaScript">
var myMessage = "Here we go again! <br>";
var numberOfRepeats = 100;
for ( i=0; i < numberOfRepeats ; i++) {
document.write(myMessage);
if ( i <0) {
document.write("Invalid Number!");
break
}
}
</script>

Listing 55.12 Continuing a while loop.

<script language="JavaScript">

var tt = 0;
xx = 55
while ( tt <= 55) {
tt += 1;
if (tt < 0) {
continue;
}
document.write ("The value of tt is " + tt +". <br> ");
}
</script>

Comments

Every language needs to have some way to document exactly what is going on, especially if you ever intend to reuse your code. It may seem obvious to you right now, as you are deep in the zone of programming your cool new script. But a few days later, you may find yourself wondering, “What was I thinking?” It's always a good idea to comment your code. I talk about comments here, in control statements, essentially because they are a way of telling the JavaScript interpreter to skip over some piece of code or comments, no matter what.

Comments are similar to a for loop that is initially and always false. JavaScript supports two kinds of comments:

You can place anything you want in either of these comments, except for one thing. Do you remember when I talked about using HTML comments to keep the older browsers from erroneously displaying javascript code? In other words, you cannot use --> in your comments unless you are really intending the script to end.

Notice also that you must place the single-line comment in front of the HTML end comment notation. This is because the JavaScript interpreter does not recognize --> as anything meaningful and gives you an error if you forget to use // before it.

Why, then, doesn't the initial line (something such as “Hide me from old browsers”) after the beginning HTML comment give you a JavaScript error? The reason is that the interpreter ignores everything else on the line containing <--. This is handy for you, because you can use this line to describe your script, and so forth.

Listing 55.13 shows both ways of displaying comments.

Listing 55.13 An example of displaying comments.

<html>
<script language = "JavaScript">
<!-- Hide this code from old browsers
one = 1
two = 2
// three = 99 everything on this line is ignored....
four = 4 ;
five = 5 ; /* everything on this line, and all
subsequent lines will be ignored, until
we get to the closing comment */
six = 6;
// remember to comment out the last line if you are using the HTML comments also -->
//You must not have JavaScript if you see this line...
</script>
</html>

Functions in JavaScript

You have now reached one of the most interesting parts of JavaScript. The heart of most scripts that you will build will consist of functions. You can think of a function as a named series of statements that can accept other variables or statements as arguments. Remember how the if statement was constructed?

if (someTest) {
zero or more statements
}
You build functions in a very similar way:
function someFunction (arguments) {
some statements
return someValue;
}

Let's discuss functions in greater detail. As I mentioned earlier in this chapter, functions are blocks of code that you can reuse over and over again just by calling the blocks by name and optionally passing some arguments them. Functions form the heart of most of the scripts you will be building and are almost as fundamental to JavaScript as classes are to Java.

You will see that JavaScript comes with many built-in functions for you to use and allows you to create your own as well. Suppose, for instance, that you wanted to use JavaScript to create a small HTML page. You can use functions to “pull out” each of the subtasks you want to do, which makes your code much easier to modify, read, and reuse. Let's look at listing 55.14.

Listing 55.14 A simple example using functions.

<html>
<head>
<script language="javaScript">
<!-- remember me?
var age = 0;
function myHeader (age) {
document.write("<TITLE>The " + age + "Year Old Page</TITLE>");
}
function myBody (date, color) {
document.write (" <body bgcolor=" + color + " >");
document.write ("<h3>Welcome to My Homepage!</h3>");
document.write ("The date is " + date + "<br>");
}
function manyLinks (index) {
if (index == 1) {
return "http://www.yahoo.com";
}
else if (index == 2){
return "http://home.netscape.com";
}
else return "http://www.idsoftware.com" ;
}
// return the title
myHeader(33);
// done for the moment! -->
</script>
</head>
<script language=JavaScript>
<!--
myBody("July 22, 1996", "#ffffff");
document.write("<a href=" + manyLinks(2) + ">Here's a link!</a>");
// -->
</script>

In this example, each function encapsulates some HTML code. You can see how you pass information into each function by means of the arguments. JavaScript passes values by reference, meaning that when you pass a value to a function, you are really just passing a value pointer to the function. (A value pointer is just an address, similar to how an house address on an envelope gives information about how to find the house.) If the function modifies that value, the value is changed for the entire script, not just the scope of the function. The result of the code is shown in figure 55.1.


FIG. 55.1

This figure displays the output from listing 55.14.

Also, notice the behavior of return. You can optionally return an explicit value back to the statement that called the function (as in return http://...). The value returned can be of any valid JavaScript type. If no value is explicitly returned, JavaScript returns true upon successful completion of the function.

Notice the difference between defining the function and calling the function. You define (or store into memory) the function by using the function keyword. None of the statements inside the function are executed until the function is called by using the function name elsewhere in the script.

You must be careful how you write your scripts when you use functions. Because JavaScript reads scripts from the top down and left to right, you cannot call functions that have not yet been read in by the interpreter.
 
Suppose, for example, you have two functions: myFirst() and mySecond(). If myFirst() appears above mySecond(), then myFirst() cannot immediately use the mySecond() function. Because of this linear interpretation and loading of code, you should instead load all of your functions first (usually in the <HEAD> area) and then call the functions afterwards. It is good practice to place your functions in the <HEAD> element, because this ensures that all of the code will be loaded into memory before your script begins to execute commands.
 

 

Remember that you don't necessarily need to pass any information to a function for it to be useful. You might create a function that writes to the page all of the many lines of HTML that make up the headers of your HTML pages. Once you have written the function once, all you have to do is call it as often as you need—saving you many keystrokes of typing later.
 

Arrays

While I am on the subject of functions, it is convenient to introduce another extremely useful construct in JavaScript—the array. An array is simply an ordered set of values that can be accessed by a common name and an index (a number representing at what place in the series that value is located). Before Netscape 3.0, you were forced to create arrays yourself by using a function you will see quite often in scripts on the Internet. Listing 55.15 shows how to create a function that builds an array for you.

Listing 55.15 An array builder.

function MakeArray(n) {
this.length = n;
for (var i = 1; i <= n; i++;) {
this[i] = " " }
return this
}
}

You may notice a new keyword here called this. this is a special keyword that refers to the current object. I talk about this and another keyword you haven't encountered, new, in later in this section. To create a new array, you simply assign the results of MakeArray to some name, as shown here:

Letterman = new MakeArray(10);

The new keyword is a way of telling JavaScript that the function to the right of it is an object constructor, and JavaScript treats it accordingly. To access values in your new array or set any of the values, use this syntax:


Letterman[1] = "A list"
Letterman[3] = "Not so popular"

In Netscape 3.0, arrays are built in, so all you need to do is use Array instead of your MakeArray function. In the previous case, this would be:

Letterman = new Array();

You can either set the size of the array when you initialize it, or just assign some null value to the highest element in the array.

Built-In Functions

There are a few built-in functions in JavaScript. Table 55.4 lists them with a short description of the function of each.

Table 55.4 Built-In Functions

Function Description
escape(str) Converts strings to HTML special characters (such as “ ” to %20).
unescape(str) Inverse of escape(). %20 to “ ”.
eval (str) Evaluates a string str as a JavaScript expression.
parseFloat (str, radix) Converts a string to a floating-point number (if possible).
parseInt (str) Converts a string to an integer value (if possible).

Now that I have touched on functions that group together statements, let’s look at the equivalent structure for data in general—the all-important Object.

Objects

Because you surely have read some part of the rest of this book (unless you decided to skip to this part first!), you have come face to face with Java objects. Basically, objects are a way of organizing data and the manipulations you might associate with that data. In Java, you have classes and methods, but in JavaScript, you have objects and functions. As I mentioned before, JavaScript comes preloaded with many very useful objects and functions. This section familiarizes you with Netscape's object model and summarizes each of the many built-in objects.

Dot Notation

JavaScript borrows from Java the system of accessing properties and methods (JavaScript freely mixes the terms function and method) by the use of the dot notation.

Basically, you access information by first naming the top-level object that contains it, as well as and all subsequent objects (or methods) that focus in on that information. Suppose you have an object called car that contains an object called door. Supposed door contains another object called doorhandle that uses a method called openDoor(). You could use this method at any time by using this syntax:

car.door.doorhandle.openDoor()

Say also that the door object has an attribute called color, and that color has a value of “Red”. You could assign that value to another variable by using a notation similar to this:

myColor = car.door.color.value ;

Methods and Properties

JavaScript objects contain data in the forms of properties and methods. Properties are basically named values that are associated with a given object. Properties are accessed through that object. In the previous example of the car, door would have the property of color.

Properties are handy and intuitive ways of storing information about an object. Methods (or functions) tend to be blocks of code that perform some operations on the object's properties. Or, methods perhaps store their results in one of the properties. The openDoor() function is a method of the object doorhandle. When I discuss the objects that are built into Navigator (see next section "Navigator Objects"), I cover their associated methods and properties as well.

Navigator Objects

When Netscape Navigator 2.0 or later versions (and more recently Microsoft Internet Explorer 3.0) opens a Web page, it immediately creates a number of objects that contain valuable information about that page. It stores information about the window, the location (the URL), the history (all of the URLs that have been visited recently), and the document (the actual text in the window). These objects are arranged in a preset hierarchy that allows you to always have a systematic way of accessing them.

Figure 55.2 illustrates the hierarchy of objects that pop into existence based on the HTML read in by the browser. Lower levels represent subobjects of the object above it.


FIG. 55.2

Netscape built-in object hierarchy.

Notice in this diagram the number of objects that are associated with HTML forms. This is a reflection of JavaScript's goal to transfer much of the form-handling ability from server-side CGIs to client-side JavaScripts. By using this diagram, you can quickly see how to access many attributes of a given page. For example, if you want to access an array of all the links on your page, you could use the following:

In JavaScript, because window is the “top-level” object and is “implied” to be in the dot notation for virtually all other objects, you can leave it off. In this instance, you would instead write:

I now touch upon JavaScript’s more important objects and briefly describe the methods and properties of each.

The Window Object

The window object is the top-level object in JavaScript. It contains all other objects except the navigator object, which is not tied to any particular window. Because most of your work is done inside a Navigator window, this is a useful object that you should become familiar with.

The window object contains methods to open and close windows, to bring up an alert dialog box (where you just click OK), to bring up a confirm dialog box (you click Yes or No), and to bring up a prompt dialog box (where you type in some information). The window object also contains properties for all frames that window contains all child windows the window creates. It also allows you to change the status line at the bottom of the window (where you see all those ticker-tape messages on many pages).

Table 55.5 lists all of the properties and methods of the window object.

Table 55.5 Properties and Methods of the Window Object

Properties Description
defaultStatus The default message in the status bar.
document The current document contained in the window.
frames An array that describes all of the frames (if any) in the window.
frame A frame object.
length Reflects the number of frames (if any) in the window.
name The name of the window.
parent Synonymous with the name of the window. Contains the frameset tags.
self Synonymous with the name of the window and refers to the current window.
status Value appears in the window's status bar. Usually only lasts a moment before overwritten by some other event.
top Synonymous with the name of the window and represents the topmost window.
window Synonymous with the name of the window and refers to the current window.
location A string specifying the URL of the current document.

Methods

alert Brings up an alert dialog box.
close Closes the window.
confirm Brings up a dialog box with Yes or No buttons and a user-specified message.
open Opens a new window.
prompt Brings up a window with user-specified text and an input box that allows the user to type in information.
setTimeout Sets a time in milliseconds for an event to occur.
clearTimeout Resets value set by setTimeout.

The Document Object

The Document object is extremely useful because it contains so much information about the current document, and it can create HTML on-the-fly with its write and writeln methods. Table 55.6 lists the properties and methods of the document object, as well as short descriptions of their purpose.

Table 55.6 Properties and Methods of the Document Object

Properties Description
alinkColor Reflects the ALINK attribute (in the <body> tag).
anchors An array listing all of the HTML anchors in the document (<a name>).
anchor An anchor object.
bgColor Reflects the value of the BGCOLOR attribute.
cookie Reflects the value of a Netscape cookie.
fgColor The value of the TEXT attribute (in the <body> tag).
forms An array listing all the forms in the document.
form A form object.
history An object containing the current browser history (links visited, number of links visited, and link URLs).
lastModified The date the document was last modified.
linkColor Reflects the LINK attribute of the <body> tag.
links An array of all HTML links in the document (<a href>).
link A link object.
location The URL of the document.
referrer The URL of the document that called the current document.
title Reflects the title of the document.
vlinkColor Reflects the color listed in the VLINK attribute.

Methods

clear Clears the window of all content.
close After an open—causes the string buffer to be written to the screen.
open Begins a string to be written to the screen. Needs a close to actually force the writing.
write Writes some expression to the current window.
writeln Same as write but adds a newline character at the end.

The Form Object

This object is created every time JavaScript encounters a <form>...</form> in your HTML documents. It contains all of the information stored in your form and can be used to submit information to a function or back to the server. Table 55.7 describes the properties and methods of the Form object.

Table 55.7 Properties and Methods of the Form Object

Property Description
action Reflects the HTML ACTION attribute of the <form> tag.
button A button object (<input type=button>).
checkbox A checkbox object (<input type= checkbox>).
elements An array listing all elements in a form.
encoding The value of the ENCTYPE attribute (for HTML uploads in Netscape).
hidden A hidden object (<input type=hidden>).
length The number of elements in the form.
method The METHOD attribute of <form>.
password A password object (<input type=password>).
radio A radio object (<input type=radio>).
reset A reset button object.
select A select object (<select>...<select>).
submit A submit button object.
target The TARGET attribute of <form>.
text A text object (<input type=text>).
textarea A textarea object (<textarea>...</textarea>).

Method

submit Submits the form to the location in the ACTION attribute.

The Navigator Object

The Navigator object is distinct from the window object in that it contains information about the browser that persists across any given window. In Netscape 3.0, JavaScript adds two new properties—an object called mimeTypes, which lists all of the mimeTypes the browser can handle; and plug-ins, which lists all of the registered plug-ins the browser can use. Table 55.8 summarizes the properties of the Navigator object (it has no associated methods).

Table 55.8 Navigator Object Properties

Property Description
appCodeName The code name of the browser, such as “Mozilla”.
appName The name of the browser, such as “Netscape”."
appVersion Contains the version information of the browser, such as “2.0 (Win95, I).”
userAgent Contains the user-agent header that the browser sends to the server to identify itself, such as “Mozilla/2.0 (Win95, I).”
mimeTypes An array reflecting all possible MIME types the browser can either handle itself or pass on to a plug-in or helper application (Netscape 3.0).
plug-ins An array of registered plug-ins that the browser currently has loaded.

The String Object

Other objects are built into JavaScript that are not specific to either the browser or the window. The first of these is the String object. This object is very useful because you can use its methods to modify and add HTML modifications without changing the string itself. One item to notice about this object is that you can string together any number of its methods to create multilayers of HTML encoding. For example,

“Hello!”.bold().blink()

would return

<blink><b>Hello!</b></blink>

Table 55.9 describes this object.

Table 55.9 Properties and Methods of the String Object

Property Description
length The number of characters in the string.

Methods

anchor Converts string to an HTML anchor.
big Encloses string in <big>...</big>.
blink Encloses string in <blink>...</blink>.
bold Encloses string in <b>...</b>.
charAt Returns the character at some index value. Index reads from left to right. If char not found, it returns a -1.
fixed Encloses string in <tt>...</tt>.
fontcolor Encloses string in <font color=somecolor>...</font>.
indexOf Looks for the first instance of some string and returns the index of the first character in the target string, or gives a -1 if not found.
italics Encloses string in <i>...</i>.
lastIndexOf Same as indexOf, only begins searching from the right to find the last instance of the search string, or -1 if not found.
link Converts string into a hyperlink.
small Encloses string in <small>...</small>.
strike Encloses string in <strike>...</strike>.
sub Encloses string in <sub>...</sub>.
substring Given a start and end index, returns the string contained by those indices.
sup Encloses string in <sup>...</sup>.
toLowerCase All uppercase characters are converted to lowercase(UpPeRcAsE becomes uppercase).
toUpperCase All lowercase characters are converted to uppercase.

The Math Object

The Math object is both a set of methods that allow you to perform higher-level mathematical operations on your numerical data and a set of properties that contain some common mathematical constants. You can use the Math object anywhere in your scripts, as long as you reference the methods like this:

Or you can use the with keyword to contain a series of math statements:

with (Math) {
foo = PI
bar = sin(foo)
baz = tan(bar/foo)
}

Table 55.10 gives you a list of the Math properties and methods.

Table 55.10 math Properties and Methods

Properties Methods
E abs
LOG2E acos
SQRT1_2 asin
LN2 atan
LOG10E ceil
SQRT2 cos
LN10 exp
PI floor
log
max
min
pow
random
round
sin
sqrt
tan

The Date Object

The final object I examine here is the Date object. This object allows you to grab information about the client's current time, year, month, date, and more. In addition, you can quickly create new date objects that can simplify keeping track of dates or time intervals between events. You can even parse a text string for date information that can be used elsewhere as a Date object. This object is most commonly used to create dynamic clocks, change page attributes (such as the background color) based on the time of day, and so on. Table 55.11 gives you a view of the Date object's methods (it has no properties).

Table 55.11 Methods of the Date Object

Method Description
getDate Returns the current date.
getDay Returns the day of the week from a date object.
getHours Returns the current number of hours since midnight.
getMinutes Returns the current number of minutes past the hour.
getMonth Returns the number of months since January.
getSeconds Returns the number of seconds past the minute.
getTime Returns the current time from the specified date object.
getTimeZoneOffset Returns the offset in minutes for the current location (either more or less than GMT, or Greenwich Mean Time).
getYear Returns the year from the Date object.
parse Returns the number of milliseconds since January 1, 1970 00:00:00 for the current locale from the Date object.
setDate Argument used to set a Date object.
setHours Argument sets the hours of the Date.
setMinutes Argument sets the minutes of the Date.
setMonth Argument sets the month value.
setSeconds Argument sets the seconds value.
setTime Argument sets the time value of the specified Date object.
setYear Argument sets the year value for the specified Date object.
toGMTString Converts a date to a string using the standard GMT conventions (for example, Wed, 24 Jul 12:49:08 GMT).
toLocaleString Converts a date to a string but is aware of the locale's convention instead of GMT. (7/24/96 10:50:02).
UTC Opposite of toGMTString. Converts a string into the number of milliseconds since the epoch.

A Final Example

I have covered a lot of ground in a brief amount of time. I encourage you to visit many Web sites, such as Netscape (http://www.netscape.com), to read their documentation about JavaScript. A good place to start your search is http://www.c2.org/~andreww/javascript/. This is an index of many JavaScript specific pages and contains links to tutorials, free scripts, and more.

As a final example of what JavaScript can do, listing 55.16 is the source code for a Web page that displays the current time every second. You can see all of the elements that have been discussed previously in this chapter somewhere within this example. Essentially, this program gets a Date object every second; parses that object for the current minutes, seconds, and hours; converts those values to a string; and then sets a form input field to that value. Using a form in this way is quite common in JavaScript. Instead of being a way to input data, the text input field becomes a “screen” to display the time.

Listing 55.16 A JavaScript clock.

<HTML>
<HEAD>
<TITLE>JavaScript Clock</TITLE>
<script Language="JavaScript">
<!-- Hide me from old browsers - hopefully
// Netscapes Clock - Start
// this code was taken from Netscapes JavaScript documentation at
// www.netscape.com on Jan.25.96
var timerID = null;
var timerRunning = false;
function stopclock (){
if(timerRunning)
clearTimeout(timerID);
timerRunning = false;
}
function startclock () {
// Make sure the clock is stopped
stopclock();
showtime();
}
function showtime () {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds()
var timeValue = "" + ((hours >12) ? hours -12 :hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue;
// you could replace the above with this
// and have a clock on the status bar:
// window.status = timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
// Netscapes Clock - Stop
// end -->
</script>
</HEAD>
<BODY bgcolor="#ffffff" text="#000000" link="#0000ff"
alink="#008000" vlink="800080" onLoad="startclock()">
<!-- main -->
<table >
<tr>
<td colspan=3>
<form name="clock" onSubmit="0">
<div align=right>
<input type="text" name="face" size=12 value="">
</div>
<center><b><font size=-1 >Welcome to My HomePage!</font></b></center><p>
</table>
</BODY>
</HTML>

Let's go through this script and see how it works to create the changing clock you will see in your browser.

After the intitial HTML code starting the page, the browser sees the <SCRIPT> tag and begins to pass the code into the JavaScript interpreter. The HTML comment <-- hides the JavaScript code from old browsers.

The next three lines are comments that JavaScript ignores.

The next two lines initialize timerID to null (a special value that acts as a placeholder), and timerRunning to false (a boolean value). The variable timerID is used in the setTimeOut and clearTimeOut function. It just acts as a name to keep track of that specific countdown.

The next five lines define a function called stopclock which tests if the timerRunning value is true. If so, it calls clearTimeout which frees up the countdown timer called timerID.

The next five lines (after a space) define a function called starclock. All startclock does is call stopclock and then the function showtime. It's important to stop the clock before calling showtime, because showtime resets the countdown timer timerID.

The next 16 lines define the heart of the script, called showtime. This function creates a new Date object called now and gets the hours, minutes, and seconds values from that object and assigns them to the variables hour, minutes, and seconds, respectively. By creating this new object every time showtime is called, the script is getting the most recent time possible, which is why the clock changes every second.

After the hours, minutes, and seconds are retrieved from the Date object, a new variable timeValue is created, which is a String object, and it assigns the corrected value of hours to this string. (The (hours >12) ? hours -12 :hours expression converts the hours from 24-hour time to 12-hour time.) The next timeValue assignments append the values of minutes and seconds to the timeValue string—correcting for tens of minutes.

The line

document.clock.face.value = timeValue

places the resulting string into the form text input field that is defined later. By assigning this value to that field, it causes that value to appear in that box on the page.

The next line in the function showtime (following the three comments) starts a countdown of one second and calls it timerID. After one second, the function showtime is called again—essentially, this is a way of calling a this function over and over again every second.

The last line in the showtime function sets the timerRunning value to the boolean true which would effect the stopclock function (breaking the one-second loop which timerID had been causing). To test this, run this script and then in the URL input window (at the top of the browser window) type

You see that the clock stops. Typing

in the URL gets the clock running again.

After the function showtime, the rest of the lines close out the script, and creates via HTML a table that contains a form called clock with one input field called face.

Notice in the <BODY> tag the onLoad="startclock()" statement. After the entire page is loaded into the window, the onLoad event handler is triggered, and the startclock function is called, which begins the script.


Previous Page TOC

| Previous Chapter | Next Chapter |

|Table of Contents | Book Home Page |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company