Previous Page TOC Next Page Home


13

Using JavaScript

Not long ago, Netscape Communications introduced a proprietary scripting language for the then upcoming Navigator 2.0. This language, called LiveScript, allowed the embedding of small programs in an HTML document to control various actions related to a Web page. The language was a scaled-down version of the powerful Java programming language, developed by Sun Microsystems for Internet and World Wide Web programming.

The idea—but not the implementation—was great. Because LiveScript was proprietary, it didn't catch on. Unlike most of the current Netscape extensions, the proprietary nature of LiveScript meant that it was unlikely to ever be supported by other Web browsers. Pages that took advantage of LiveScript were definitely in the category of "Netscape Navigator Only" pages and, it seemed, would be so for a long time.

Then, suddenly, LiveScript was no more, and in its place a new scripting language called JavaScript appeared. In reality, the two languages are basically identical—like a Ford Escort and a Mercury Tracer, two different nameplates for the same chassis. But JavaScript is backed and supported not only by Netscape, but also by Sun Microsystems, America Online, Apple Computers, Borland International, MacroMedia, Paper Software, Silicon Graphics, the Santa Cruz Operation, and Toshiba Corporation, just to mention a few of the companies that stand behind the endorsement of JavaScript as the new, open Internet scripting language standard.

With this critical mass of Web movers and shakers behind it, JavaScript is emerging as a de facto standard for general-purpose Web programming. If you want to learn one way to build functions into your Web page, JavaScript is the name to know.

In this chapter, you


Although JavaScript is expected to gain wide acceptance, it's understood today only by the various flavors of Netscape Navigator 2.0 and above. For the time being, you must accept that your JavaScript-coded functions are available only to users of Navigator 2.0 and higher. If you want a function to be available to a wider audience, you might need to use a CGI script. (See Chapter 12, "Creating Interactive Forms and Image maps.")

JavaScript is an emerging language, and it's still changing and growing rapidly. To keep up with JavaScript specification and any new features, you'll want to visit the JavaScript reference information at Netscape often. See the section titled "Learning More About JavaScript," near the end of this chapter.

Introducing JavaScript

According to a press release issued by Netscape Communications, "JavaScript is an easy-to-use object-scripting language designed for creating live online applications that link together objects and resources on both clients and servers. JavaScript is designed for use by HTML page authors and enterprise application developers to dynamically script the behavior of objects running on either a client or server." So there.

What Is JavaScript, Really?


To learn about the other common scripting language, CGI, see Chapter 12.

Put into simple English, Netscape enables you, when you use JavaScript, to add functionality to your Web pages, which in the past would have demanded access to complex CGI-based programs on a Web server. In many ways, JavaScript is a lot like Visual Basic—the user-friendly programming language developed by Microsoft—in that people with little or no programming knowledge can use JavaScript (with study, patience, practice, and a positive attitude). These novices can quickly and easily create complex Web-based applications without having to deal with all the background complexities such activities involve.

What makes JavaScript so different, however, is the unique way in which it integrates itself with the World Wide Web. Instead of being stored as a separate file—like a CGI script—JavaScript code is included as part of a standard HTML document, just like any other HTML tags and elements. In fact, you can type your JavaScript code directly into a document in the Netscape Editor. (See the section titled "Using JavaScript in the Netscape Editor," later in this chapter.)

In addition, unlike CGI scripts, which run on a Web server, JavaScript scripts are run by the Web browser itself. Thus, they are portable across any Web browser that includes JavaScript support, regardless of the computer type or operating system.

Why Would I Want to Use JavaScript?


A server-side version of JavaScript will soon emerge to replace the Perl and Bourne shell CGI scripts (see Chapter 12), making JavaScript both the server and the client scripting language.

The answer to this question depends, to a certain extent, on exactly what capabilities are eventually included as part of the JavaScript language. It is likely, however, that scripts written using JavaScript will eventually be able to control all aspects of a Web page or Web form, and to communicate directly with plug-ins displayed on a Web page and with compiled Java applets.

In fact, Paper Software—the developers of the WebFX VRML Plug-in—is working on such technology for future versions of WebFX. By using these capabilities, you will eventually be able to create fully interactive 3-D virtual worlds on the World Wide Web that can be modified and controlled by Java applets.


Don't confuse JavaScript with Java, a more complex, more powerful language for creating Web-based applications called applets. JavaScript is based on Java but is another animal.

Apart from such futuristic possibilities, what JavaScript enables you to do now is perform many simple (and not so simple) programming tasks at the Web browser (or client end) of the system, instead of relying on CGI scripts at the Web server end. In addition, JavaScript enables you to control with far greater efficiency the validation of information entered by users on forms and other data-entry screens. And finally, when integrated with frames, JavaScript brings a wide variety of new document presentation options to the Web publishing domain.

Ease of Use

Unlike Java, JavaScript is designed for nonprogrammers. As such, it is relatively easy to use and is far less pedantic about details such as the declaration of variable types. In addition, you do not need to preprocess, or compile, JavaScript code before it can be used—something you need to do with many other programming languages, including Java.

Increasing Server Efficiency

As more people flood the Web, popular Web sites are being pushed to the limit of their current processing capabilities. As a result, Web operators are continually looking for ways to reduce the processing requirements for their systems—to ward off the need for expensive computer upgrades. This was one of the main reasons for the development of client side imagemaps like those discussed in Chapter 12, "Creating Interactive Forms and Imagemaps."

With the introduction of JavaScript, some exciting new performance options are now available to Web publishers. For example, say you have created a form that people use to enter their billing details for your online ordering system. When this form is submitted, the first thing your CGI script needs to do with it is validate the information provided and make sure that all the appropriate fields have been filled out correctly. You need to check that a name and address have been entered, that a billing method has been selected, that credit-card details have been completed—and the list goes on.

But what happens if your CGI script discovers that some information is missing? You would need to alert the user that there are problems with the submission and then ask him to edit the details and resubmit the completed form. This entire process is very resource-intensive. First, the Web server needs to allocate a dedicated resource to perform all the validation and checks, and second, when there are errors, two additional data transmissions must be handled by the server—one to alert the user of errors and one to receive the updated information.

On the other hand, by moving all the validation and checking procedures to the Web browser—through the use of JavaScript—you remove the need for any additional transactions, because only one "valid" transaction will ever be transmitted back to the server. And, in addition, because the Web server does not need to perform any validations of its own, there is a considerable reduction in the amount of server hardware and processor resources required to submit a complex form.

JavaScript and Web Service Providers

With an increasing number of Web service providers severely limiting the availability of CGI script support for security reasons, JavaScript offers an excellent method of regaining much of the missing CGI functionality. It moves tasks that would previously have been performed by a server side CGI script onto the Web browser.

Most Web service providers usually furnish some form of basic CGI script, which can take a form submitted by a user and perform basic processing operations such as saving it to disk or mailing it to the site's owner. When it comes to more complex forms, however, in the past the only alternatives were to find another service provider or set up your own Web server. But now, with JavaScript, this no longer is the case.

By using a Web service provider's basic form-processing CGI scripts with JavaScript routines buried in the Web page itself, there are very few form-based activities that cannot be duplicated on even the most restrictive and security-conscious Web service provider's site. In addition, after the full integration of Java, JavaScript, and plug-ins has been achieved, you will be able to do things on a Web page that would never have been considered possible previously with even the most capable CGI script.

Submitting Forms Without CGI

To learn about CGI forms, see Chapter 12.

The ACTION attribute of the <FORM> tag has traditionally been associated with a CGI script located on a Web server. But, in fact, any URL can be assigned to the ACTION attribute. Doing so, however, has little value unless the resource associated with the URL can process the contents of the form in some way.

That having been said, there is one type of URL—apart from a CGI script—that can process the results of a form in a meaningful way—mailto. For example, if you included the following <FORM> tag on a page, clicking the SUBMIT button would e-mail the contents of the form to my e-mail address:

<FORM METHOD="POST" ACTION="mailto:wtatters@world.net">

In the past, however, using such an ACTION could be relied upon only when the contents of the form were not vital, because there was no way to validate the information. But by using JavaScript, you can now validate the data before it is e-mailed and even perform basic calculations or other processing.


To make use of the ACTION attribute with mailto, the visitor's browser must be configured to open an e-mail client in response to a mailto link. (See Chapter 5.)

The javascript: Protocol

To complement the use of the mailto: protocol within the ACTION attribute, a new URL and protocol specifically for JavaScript has also been introduced. This new URL takes the following form:

javascript:function()

where function() can be replaced by any of the functions and methods you will learn about later in this chapter. This new URL can be used in place of any of the previously discussed URLs: inside <FORM> tags, <A> tags, and even inside the <AREA> tag of a client-side image map.

The <SCRIPT> Tag


You don't need to use the <SCRIPT> tag when you enter your JavaScript code directly in the Netscape Editor. See the section titled "Using JavaScript," in the Netscape Editor, later in this chapter.

To accommodate the inclusion of JavaScript programs in a normal HTML document, Netscape has proposed the introduction of a new <SCRIPT> tag. By placing a <SCRIPT> tag in a document, you tell the browser to treat any lines of text following the tag as script—rather than as content for the Web page. This action then continues until a corresponding </SCRIPT> tag is encountered, at which point the Web browser reverts to its usual mode of operation—treating text as Web content.


In general, you need not use the LANGUAGE attribute. Navigator 2.0, the only browser that supports JavaScript, assumes the language is JavaScript if no LANGUAGE is specified.

When used in a document, a script tag may include an optional LANGUAGE attribute to declare the scripting language to be used. Currently, the two possible values for this attribute are LANGUAGE="LiveScript" and LANGUAGE="JavaScript".

The Structure of a JavaScript Script

When you include any JavaScript code in an HTML document, apart from using the <SCRIPT> tag, you should also follow a few other conventions:

As a rule, the <SCRIPT> tag should be placed inside the <HEAD> and </HEAD> tags at the start of your document and not inside the <BODY> tags. This is not a hard and fast requirement (as you will learn latter), but it is a standard you should adopt whenever possible. Basically, because the code for your scripts is not to be displayed on the Web page itself it should not be included in the <BODY> section, but instead in the <HEAD> section with all the other control and information tags such as <TITLE> and <META>.


When you enter JavaScript in the Netscape Editor, no comment tags are entered automatically. You may enter them with the Editor's Insert Tag function or in an HTML source editor. (See Chapter 9.)

Because Web browsers that are not JavaScript-aware will attempt to treat your JavaScript code as part of the contents of your Web page, it is important to surround your entire JavaScript code with a <![--] comment tag [--]>. Doing this will ensure that non-JavaScript[nd]aware browsers can at least display your page correctly, if not make it work properly.

Unlike HTML, which uses the <![--] comment tag [--]>, comments inside JavaScript code use the // symbol. Any line of JavaScript code that starts with this symbol will be treated as a comment and ignored.

Taking these three points into consideration, the basic structure for including JavaScript code inside an HTML document looks like this:

<HEAD>

<TITLE>Test script</TITLE>

<SCRIPT>

<![--] Use the start of a comment tag to hide the JavaScript code

  Your JavaScript code goes here

// close the comment tag on the line immediately before the </SCRIPT> tag [--]!>

</SCRIPT>

</HEAD>

<BODY>

   Your Web document goes here

</BODY>

</HTML>

The SRC Attribute

Besides the LANGUAGE attribute, the <SCRIPT> tag can also include a SRC attribute. Doing this allows a JavaScript script stored in a separate file to be included as part of the current Web page. This is a handy option if you have several Web pages that all use the same JavaScript code and you don't want to type the scripts separately into each page.

When used like this, the <SCRIPT> tag takes the following form:

<SCRIPT SRC="http://script.js">

You must follow certain procedures when using the SRC attribute in the Netscape Editor. See Using SRC in the Editor later in this chapter.

In this form, script can be any relative or absolute pathname (see Chapter 5, "Linking Anywhere, Everywhere"), and .js is the file extension for a JavaScript file, a simple text file containing just the JavaScript code (and not including the <SCRIPT> tag).

Using JavaScript in the Netscape Editor

Observing a few important differences, you may enter JavaScript code directly into the Netscape Editor, just as you would (well, almost) in any HTML source editor. (See Chapter 9, "Editing HTML Source Code.") The code itself is visible when you view the page in the Editor (see Figure 13.1); when you view the document in the Netscape Browser, the proper effects of the script appear instead.


It is the recommendation of this book that you not, as a rule, enter your JavaScript code in the Editor. Using an HTML source editor is the recommended approach, and all examples in this chapter are presented as they should be coded in an HTML source editor, not in the Netscape Editor.

Why not use the Netscape Editor for JavaScript?

WThe Editor provides you with no way to enter the script in the header, rather than the body, of the document. As you'll learn throughout this chapter, entering the script in the header is almost always the way to go.

WThe Editor provides no mechanism through which to use attributes to the <SCRIPT> tag. To use attributes, you must enter your script in the Editor, then open the file in an HTML source editor to add the attributes.

WThe JavaScript support in the Editor is rather clumsily implemented. This will probably be remedied in a later version of Gold (after version 2.01), so it's important for you to know, generally, how to use JavaScript in the Editor. But for now, do your JavaScript work in an HTML source editor, until Netscape does a better job.

To enter JavaScript code in the Editor, you must observe two important differences from entering the code in an HTML source editor:


Figure 13.1. Entering a simple JavaScript in the Editor.


Figure 13.2. Assigning the JavaScript Client Character property to the script code.


Figure 13.3. The HTML source for the document shown in Figures 13.1 and 13.2, showing that the <SCRIPT> tags were added automatically.


Figure 13.4. The document shown in Figures 13.1-13.3, viewed through the browser to show the script's effects.

Basic JavaScript Commands

At its heart, JavaScript uses an object-oriented approach to computer programming. This basically means that all the elements on a Web page are treated as objects that are grouped together to form a completed structure.

Using this structure, all the elements of a single Web page are said to be contained within a base object container called window. Inside the window object are a set of smaller containers (or objects) that hold information about the various elements of a Web browser page. These are some of the main objects:

location Inside the location object is information about the location of the current Web document, including its URL and separate components such as the protocol, domain name, path, and port.
history The history object holds a record of all the sites a Web browser has visited during the current session, and it also gives you access to built-in functions that enable you to change the contents of the current window.
The document object contains the complete details of the current Web document. This includes all the forms, form elements, links, and anchors. In addition, it provides many types of functions that enable you to programmatically alter the contents of items such as text boxes, radio buttons, and other form elements.

Properties and Methods

Within each object container, there are two main types of resources you can access.

The first type are called properties. Properties are basically variables that hold a value associated with the object you are interested in. For example, within the document object, there is a property called title that contains the title of the current document as described by the <TITLE> tag.

In JavaScript, you could obtain the value of this property by using the statement document.title. The first part of the statement tells JavaScript which object you want to work with, and the second part—following the dot—represents the physical property itself.


Netscape's online documentation covers in detail all the properties and methods associated with each object. See the section titled "Learning More about JavaScript," later in this chapter.

In addition to properties, most objects also have special functions associated with them called methods. Methods are basically programming commands that are directly related to a particular object. For example, the document object has a method associated with it that enables you to write text directly onto a Web page. This method takes the following form:

document.write( "Hello world") ;

As was the case for properties, you describe a method by first declaring the object it is associated with, followed by a dot, and then indicating the method itself. In this example, the method must be assigned a value by including the relevant information inside the parentheses () that follow the method name. It is important to realize, however, that the parentheses must be included even if no values are assigned to the method, as is the case for the toString() method of the location object. This method is used to convert the current document's URL into a form suitable for use with other methods such as document.write().

By combining these methods and the document.title property mentioned previously into an HTML document like the following one, you would produce the results shown in Figure 13.5.


All examples in this chapter are presented as you should code them in an HTML source editor, not in the Netscape Editor.

<HTML>

<HEAD>

<TITLE>Test JavaScript</TITLE>

<SCRIPT LANGUAGE="JavaScript">

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

document.write( location.toString() ) ;

</SCRIPT>

</HEAD>

</HTML>


Figure 13.5. The results of your first JavaScript script.


Method, property, function, and variable names all case-specific; you must capitalize them exactly as shown. For example, Location.toSTRing() will not work in place of location.toString().

Events and JavaScript

Although implementing methods such as document.write() to create Web pages might have some uses, the real power behind JavaScript lies in its capability to respond to events generated by a Web page.

Events are actions that occur on a Web page, normally when a user interacts with the page in some way. For example, when a person enters a value into a text box on a form, or clicks a submit button, a series of events are triggered inside the Web browser, all of which can be intercepted by JavaScript programs, usually in the form of functions.

Functions

JavaScript includes built-in objects and functions that perform mathematical operations, string manipulation, and date and time calculations. See Netscape's online JavaScript documentation.

Functions are very similar to methods. The difference, however, is that whereas methods are associated with a specific object, functions are standalone routines that operate outside the bounds of an object. To define a function for the current Web page, you would write something like this:

<SCRIPT LANGUAGE="JavaScript">

function functionName( operands ) {

  The actions to be performed by your function go here

}

</SCRIPT>

functionName is any unique name you choose, and operands is a list of any values you want sent to the function. Following the function definition and inside the set of braces, { }, you include the list of instructions you want the function to perform. These could be a set of calculations, validation tests for a form, or just about anything else you can think of.

Assigning Functions to Events

After you have your functions defined, the next thing you need to do is assign them to the various events you want trapped. You do this by assigning what are called event handlers to the various elements of a Web page or form. Currently, you can set the following event handlers:

onFocus Whenever a user enters a specified field
onBlur Whenever a user leaves a specified field
onSelect Whenever a user selects the contents of a specified field
onChange Whenever a user changes the contents of a specified field
onClick Whenever a user clicks a specified button
onMouseOver Whenever a user places the mouse cursor over a specified field
onSubmit Whenever a user submits a specified form
onLoad Whenever a Web page is loaded or reloaded
onUnload Whenever the current Web page is changed

To specify functions that should be associated with any of these events, all you need to do is include the appropriate event handler as an attribute of the field you want to control. For example, take a standard form with a couple of text fields and a submit button as shown here:

<FORM METHOD="POST" SRC="../cgi-bin/form">

<INPUT TYPE="TEXT" NAME="username">

<INPUT TYPE="TEXT" NAME="emailAddress">

<INPUT TYPE="SUBMIT">

</FORM>

By adding onSubmit="return checkform( this )" to the <FORM> tag, the function called checkform() will be run before Navigator 2.0 submits the form. In checkform(), you can do any checks you want and, if there are any problems, halt the form submission and ask the user to fix them. The this parameter, inside the parentheses (()), is used to tell the checkform() function which form object is associated with the <FORM> tag.

In addition, you can do checking field by field, by including either onChange or onBlur event handlers in each <INPUT> tag. Because the onBlur handler is called each time a person leaves a field, it is ideal for input validation.


JavaScript introduces a new <INPUT> type called button, which simply places a button on the Web page.

You can also include onClick events in buttons like the submit button which will be activated whenever the user clicks the specified button. For example, <INPUT TYPE="SUMBIT" onClick="processclick()"> would launch a function called processclick() whenever the submit button was clicked.

Variables

In addition to properties, JavaScript also enables you to assign or retrieve values from what are called variables. A variable is basically a user-defined container that can hold a number, some text, or an object. But unlike most high-level languages that force you to limit the contents of each variable to a specific type, in JavaScript variables are said to be loosely typed language. This means that you don't need to specify the type of information a variable contains when the variable is created. In fact, the same variable can be assigned to data of different types depending on your requirements.

To declare a variable for a JavaScript program, you would write this:

var variablename = value ;

Variable names (and function names) can consist of the letters a through z, the numbers 0 through 9, and the underscore (_) symbol. But names cannot start with a number.

In this form, variablename is any unique name you choose. The equals (=) sign following the variablename is called an assignment operator. It tells JavaScript to assign whatever is on the right side of the = sign—value—as the contents of the variable. This value can be a text string, a number, a property, the results of a function, an array, a date, or even another variable. Here's an example:

var name = "Ned Snell" ;

var age = 34 ;

var title = document.title ;

var documenturl = location.toString() ;

var myarray = new Array(10);

var todaysdate = new Date();

var myname = anothername ;

If a variable is inside a function, you can access the contents of the variable only from inside the function. If the variable is inside a <SCRIPT> block but not in a function, you can access the contents of the variable anywhere in the page.

Operators and Expressions

After a variable has been defined, you can work with its contents, or alter them, by using what are called operators. Table 13.1 lists some of the more popular operators provided by JavaScript and includes an example that demonstrates the use of each. (As before, for a full list of all the supported operators, refer to the online JavaScript documentation.)


The examples shown in the second column of Table 13.1 are called expressions. Basically, an expression is any valid set of variables, operators, and expressions that evaluate to a single value. For example, b + c evaluates to a single value, which is assigned to a.

Operator
Example
Description
+ a = b + c Add variables b and c, and assign the result to variable a.
- a = b - c Subtract the value of variable c from variable b, and assign the result to variable a.
* a = b * c Multiply variable b by variable c, and assign the result to variable a.
/ a = b / c Divide variable b by variable c, and assign the result to variable a.
% a = b % c Obtain the modulus of variable b when it is divided by variable c, and assign the result to variable a. (Note: modulus is a function that returns the remainder.)
++ a = ++b Increment variable b by 1, and assign the result to variable a.
[--] a = [--]b Decrement variable b by 1, and assign the result to variable a.

The + and += operators can be used with string variables and numeric variables. When they're used with strings, the result of a = "text" + " and more" is a variable containing "text and more".

There is also a special set of operators that combine the assignment function (=) and an operator into a single function. Such operators are called assignment operators. Table 13.2 lists the assignment operators provided by JavaScript.

Assignment Operator
Example
Description
+= a += b This is equivalent to the statement a = a + b.
-= a -= b This is equivalent to the statement a = a - b.
*= a *= b This is equivalent to the statement a = a * b.
/= a /= b This is equivalent to the statement a = a / b.
/= a %= b This is equivalent to the statement a = a % b.

JavaScript Programming

To tie together all the event handlers, methods, parameters, functions, variables, and operators, JavaScript includes a simple set of programming statements that are similar to those provided by Java and the old BASIC programming language.

If you have any programming experience at all, spending a few minutes browsing through the list of supported statements discussed in Netscape Communication's online documentation will set you well on your way toward creating your first JavaScript programs. But for those of you who don't have the experience, the following section includes a quick crash course on basic programming.

What Is a Program?

Regardless of what language you use, a program is simply a set of instructions that describe to a computer some action, or group of actions, you want it to perform. In the most basic case, this set of instructions starts at the beginning of a list of code and works through each instruction in the list one at a time, until it reaches the end:

<SCRIPT LANGUAGE="JavaScript">

// start of program - NOTE: lines that start with '//' are treated as comments

document.write( "step one") ;

document.write( "step two") ;

// end of program

</SCRIPT>

It is rare, however, that you will ever want a program to proceed straight through a list of steps—especially in JavaScript—because it would be easier to write the messages on the screen using HTML than to code them by using JavaScript. For this reason, most programming languages include a basic set of instructions that enable you to control the flow of the instructions.

The if Statement

The first such instruction is called the if statement. Basically, it enables you to perform tests inside program code, to determine which parts of the program should be run under any given situation. For example, assume that you have a Web form that asks whether a person is male or female. In such cases, you might want to respond to the person using a gender-specific response, based on the indicated sex:

if ( form.theSex.value == "male" ) {

   document.write("Thank you for your response, Sir" ) ;

}

if ( form.theSex.value == "female") {

   document.write("Thank you for your response, Madam" ) ;

}

If this piece of code were run and the property form.theSex.value had been assigned a value of "male", the first document.write() method would have been called. If it had been assigned a value of "female", the second statement would have been displayed.

The block of code next to the if statement performs comparison between the property form.theSex.value and the word "male". This comparison is controlled by what are called comparison operators. In this case, a test for equivalence was performed as signified by the == symbol. Table 13.3 lists the comparison operators currently recognized by JavaScript.

Operator
Operator Description
Notes
== Equal a == b: tests to see if a equals b.
!= Not equal a != b: tests to see if a does not equal b.
< Less than a < b: tests to see if a is less than b.
<= Less than or equal to a <= b: test to see if a is less than or equal to b.
>= Greater than or equal to a >= b: tests to see if a is greater than or equal to b.
> Greater than a > b: tests to see is a is greater that b
The if. . .else Statement

The preceding example could have also been written in a slightly different way, by using a different version of the if statement that incorporates an else statement:

if ( form.theSex.value == "male" ) { document.write("Thank you for your response, Sir" ) ; } else { document.write("Thank you for your response, Madam" ) ; }

In this example, because there is no need for a second if test—because a person can be only male or female—the else statement was used to tell the program to display the second message if the first test failed.

Looping Statements

On occasion, you will want a group of statements to run multiple times rather than just once. Two looping statements are supported by JavaScript to carry out this task. The first kind of statement, called a for loop, is ideal for situations in which you want a group of instructions to occur a specified number of times. And the second kind, the while loop, is better suited to situations in which the number of loops required is to be determined by an outside source.

for Loops

The basic structure of a for loop looks like this:

for (var count = 1; count <= 10; ++count ) {

  your statements go here

}

In this example, a variable called count is declared and set to a value of 1. Then a test is made to see whether the value of count is less than or equal to 10. If it is, all the statements inside the braces, {}, following the for statement are executed once. Then, the value of count is incremented by 1 by the statement ++count, and the count <= 10 test is performed again. If the result is still true, all the instructions inside the braces are executed again. This process then proceeds until the value of count is greater than 10, at which stage the for loop ends.

while Loops

The basic structure of a while loop looks like this:

while ( contition ) {

  your statements go here

}

Unlike the for loop, which has a built-in increment mechanism, the only test required for a while loop is a true result from the condition test following the while statement. This test could be an equivalence test, as in a == b, or any of the other tests mentioned previously in the if statement.

As long as this condition tests true, the statements inside the braces following the while loop will continue to run forever—or at least until you close your Web browser.


When using while loops, avoid creating endless loops, or infinite loops. If you do create an endless loop, you must shut down the browser to kill it.

Task: Creating Random Link Generators

A random link generator is basically a link that takes you to different locations every time you click it. In the past, the only way to implement such a link was through the use of a CGI; but with JavaScript, all the previous server side processing can now be performed by the Web browser itself.


An inline <SCRIPT> tag is one that is embedded in the <BODY> section of an HTML document rather than in the <HEAD> section, as is the more common practice.

In the sections that follow, you will learn how to create three different random-link generators. The first uses an inline <SCRIPT> tag and a single function, the second uses event handlers, and the third examines the use of arrays within a script.

Because the JavaScript code for this generator will be incorporated in a standard HTML document, open the text editor or HTML editor you normally use for designing Web pages and create a new file called random.html.

In this new file, create a basic document framework like the following one. You should recognize all the elements of this document from previous chapters, including the <A>. . .</A> tag combinations on the third-from-last line. If you were to run this document as it is, you would see a result like the one shown in Figure 13.6.

<HTML>

<HEAD>

<TITLE>Random Link Generator</TITLE>

</HEAD>

<BODY>

<H1>My random link generator</H1>

Click <A HREF="dummy.html">here</A> to visit a randomly selected site

from my list of favorites.

</BODY>


Figure 13.6. Clicking the link loads a document called dummy.html.

Now it's time to add some JavaScript code to turn the link into a random-link generator. First, add a <SCRIPT> tag to the <HEAD> section immediately after the <TITLE> tag block:

<TITLE>Random Link Generator</TITLE>

<SCRIPT LANGUAGE="JavaScript">

<!-- the contents of the script need to be hidden from other browsers

  the JavaScript code goes here.

// End of script -->

</SCRIPT>

</HEAD>

The next step involves adding the code that generates the random links, based on a list of your favorite sites. Inside the <SCRIPT> tag—and comment tag—you will create a function called picklink(). So you first define the framework for a function like this:

function picklink() {

  your JavaScript code goes here.

}

And finally, here's the code that actually makes the picklink() function work:

function picklink() {

var linknumber = 4 ;

var linktext = "nolink.html" ;

var randomnumber = Math.random() ;

var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;

if ( linkselect == 1 )

   { linktext="http://www.netscape.com/" }

if ( linkselect == 2 )

   { linktext="http://www.webcom.com/taketwo/" }

if ( linkselect == 3 )

   { linktext="http://java.sun.com/" }

if ( linkselect == 4 )

   { linktext="http://www.realaudio.com/" }

document.write('<A HREF="' + linktext + '">here.</A>') ;

}

To help you understand what this code is doing, I'll examine it section by section. The first two lines following the function definition declare some work variables for the function: linknumber tells the function how many links it has to choose from when selecting a random link, and linktext is a work variable used to hold the value of the URL for the selected random link.

The next line—var randomnumber = Math.random() ;—declares a variable called randomnumber and assigns a randomly selected decimal value between 0 and 1 to it by calling a special built-in function named Math.random(). The next line then takes the randomnumber variable and uses it to create a second number called linkselect, which will contain an integer number between 1 and the value set in linknumber. (An integer number is any whole number that does not contain any decimals. 1, 2, and 10 are integers, 1.3, 2.356, and 10.9999 are called decimal or floating point numbers.)


The Math.random() function is still under development as this book goes to press. If it does not make the final release of 2.0, you will need to use the replacement random() function shown below. This function is based loosely on one developed by Bob Jamison (rjamison@gothamcity.jsc.nasa.gov):

function random() {
var curdate = new Date()
var work = curdate.getTime() + curdate.getDate()
return ( (work * 29 + 1) % 1024 ) / 1024
}

Simply add this function before the // End of script [--]> line and replace the Math.random() statement with random().

The set of if statements that follows then checks the randomly selected value assigned to linkselect and, when a match is found, assigns a URL to the variable linktext. You can add any number of URLs you like here, but remember that you need to alter the value of linknumber so that it reflects how many links you have defined.

After you have a URL assigned to linktext, the final step in the process is to create the physical link by using a document.write() method. You do this by writing this line:

document.write('<A HREF="' + linktext + '">here.</A>') ;

The value inside the parentheses takes advantage of JavaScript's capability to add strings of text together. In this case, '<A HREF="', the value of linktext, and '">here.</A>' are added together to create a properly formed link tag.

With the function definition complete, all that now remains to be done is to replace the original <A HREF= tag from the basic framework with the new link created by picklink(). This can be done in various ways, but the simplest method is by embedding a call to picklink() inside the body of your document, as shown here:

Click <SCRIPT LANGUAGE="JavaScript">picklink()</SCRIPT>

 to visit a randomly selected site from my list of favorites.

Here is the completed HTML document:

<HTML>

<HEAD>

<TITLE>Random Link Generator</TITLE>

<SCRIPT LANGUAGE="JavaScript">

<!-- the contents of the script need to be hidden from other browsers

function picklink() {

var linknumber = 4 ;

var linktext = "nolink.html" ;

var randomnumber = Math.random() ;

var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;

// Add as many links as you want here

if ( linkselect == 1 )

   { linktext="http://www.netscape.com/" }

if ( linkselect == 2 )

   { linktext="http://www.webcom.com/taketwo/" }

if ( linkselect == 3 )

   { linktext="http://java.sun.com/" }

if ( linkselect == 4 )

   { linktext="http://www.realaudio.com/" }

// Remember to alter linknumber so it reflects the number of links you define

document.write('<A HREF="' + linktext + '">here</A>') ;

}

// End of script -->

</SCRIPT>

<BODY>

<H1>My random link generator</H1>

Click <SCRIPT LANGUAGE="JavaScript">picklink()</SCRIPT>

 to visit a randomly selected site from my list of favorites.

</BODY>
To Create a Random Link Generator Using an Event Handler

Besides being bad style-wise, using inline <SCRIPT> tags can cause unpredictable problems when images are displayed on a page. To avoid such difficulties, the safest way to work with scripts is by using them only in the <HEAD> block, where at all practical.

But this situation poses a problem for your random link generator, which needs to alter the value of a link each time it is used. If you can't include <SCRIPT> tags in the <BODY> of a document, how can the link be randomly selected?

Whenever you click a link, a button, or any form element, Navigator 2.0 generates an event signal that can be trapped by one of the event handlers. By taking advantage of this fact, and the fact that each link in a document is actually stored as an object that can be referenced by JavaScript, you will find it surprisingly easy to alter your existing script to avoid the need for an inline <SCRIPT> tag.

First, look at the changes that need to be made in the body of the document to accommodate the use of an event handler. In this part of the task, the inline <SCRIPT> tag is replaced by a normal <A> tag as shown here:

Click <A HREF="dummy.html">here</A> To visit a randomly selected site

from my list of favorites.

After this is done, you need to associate an onClick event handler with the link by including the handler as an attribute of the <A> tag. When onClick is used as an attribute, the value assigned to it must represent a valid JavaScript instruction or function call. For this task, you want to call the picklink() function created previously and make the URL it selects overwrite the default URL defined in the <A> tag as HREF="dummy.html".


The this statement tells JavaScript to reference an object without having to know its name or location. In the example, this points to the link object and this.href indicates the href property. By assigning a new value to this.href, you change the destination URL.

This job is easy to do because each link is actually stored as an object of type link, and the link type contains the same properties as the location object. As a result, all you need to do is assign a new value to the HREF property of the link, in the onClick event handler, as shown here:

Click <A HREF="dummy.html" onClick="this.href=picklink()">here</A>

 To visit a randomly selected site from my list of favorites.

With the onClick handler set up, all you need to alter in the picklink() function is the document.write() method. Because you are no longer physically writing anything onto the Web page, the document.write() function needs to be removed. But in its place, you need some way for the value of linkselect to be sent back to the this.href property.

You achieve this by using the return statement, which sends a value back from a function call, as shown here:

return linkselect ;

In the picklink() function, you need to replace

document.write('<A HREF="' + linktext + '">here</A>')

with this new statement.


If you get error messages when using the built-in Math.random() function, you may need to use the replacement random() function discussed earlier in this chapter.

If you examine the completed text for this new HTML document, you will notice that there is very little difference between it at the preceding task, except for the removal of the inline <SCRIPT> tag and the replacement of document.write() with a return statement:

<HTML>

<HEAD>

<TITLE>Random Link Generator with events</TITLE>

<SCRIPT LANGUAGE="JavaScript">

<!-- the contents of the script need to be hidden from other browsers

function picklink() {

var linknumber = 4 ;

var linktext = "nolink.html" ;

var randomnumber = Math.random() ;

var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;

if ( linkselect == 1 )

   { linktext="http://www.netscape.com/" }

if ( linkselect == 2 )

   { linktext="http://www.webcom.com/taketwo/" }

if ( linkselect == 3 )

   { linktext="http://java.sun.com/" }

if ( linkselect == 4 )

   { linktext="http://www.realaudio.com/" }

return linktext;

}

// End of script -->

</SCRIPT>

<BODY>

<H1>My random link generator</H1>

Click <A HREF="dummy.html" onClick="this.href=picklink()">here</A>

 to visit a randomly selected site from my list of favorites.

</BODY>

To Create a Random Link Generator Using an Array

The only problem with the preceding example is the need to keep adding additional if tests for each new link you want to include in your random list of favorites. To get around this difficulty, and to streamline the appearance of the script considerably, JavaScript provides a mechanism that enables you to create lists of variables—or what are called arrays.


Arrays in JavaScript work differently from arrays in other languages. The arrays in this example are technically objects, but JavaScript enables you to treat them like arrays. Refer to Netscape's JavaScript documentation for more about Arrays.

An array is a list of variables that are all referenced by the same variable name. For example, an array called mylinks[] could be used to contain a list of all the links used by the picklink() function. The value of each link in the list is then referenced by the placement of a numeric value inside the square [] brackets: The first variable can be found with mylinks[1], the second with mylinks[2], and so on.

To take advantage of the possibilities offered by arrays, you first need to create a small function known as a constructor method. This function is needed because arrays are really objects. The online JavaScript documentation listed in the preceding Note provides additional information about how such a constructor should look. The MakeArray() constructor is based on a function created by Brenden Eich—the programmer at Netscape Communications responsible for the creation of JavaScript. Here is the MakeArray() function:

function MakeArray(n) {

// Initial concept Brenden Eich - Netscape Communications

   this.length = n;

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

       { this[i] = 0 }

   return this

   }

You need to include this function in your JavaScript code whenever you want to use arrays in a program. After the MakeArray() function has been defined, you can create the mylinks[] array discussed previously by writing

mylinks = new MakeArray( value )

in which value is the number of elements to be declared in the array.

You can then fill the mylinks[] array with values by simply assigning them as you would any other variable. Here's an example of an array with five elements with a URL assigned to each:

<SCRIPT LANGUAGE="JavaScript">

<!-- the contents of the script need to be hidden from other browsers

mylinks = new MakeArray( 5 ) ;

mylinks[1] = "http://www.netscape.com/" ;

mylinks[2] = "http://www.webcom.com/taketwo/" ;

mylinks[3] = "http://java.sun.com/" ;

mylinks[4] = "http://www.realaudio.com/" ;

mylinks[5] = "http://www.worlds.com/" ;

Now that you have a list of URLs defined, you'll modify the original picklink() function so that it selects a link by choosing from those included in the array, instead of by using if tests. Here is the new code:

function picklink() {

   linknumber = mylinks[0] ;

   randomnumber = Math.random() ;

   linkselect = Math.round( (linknumber-1) * randomnumber ) + 1 ;

   return mylinks[ linkselect ] ;

}

The first change you need to make deals with the value assigned to linknumber. In the previous examples, you set this value manually, but now you need to set it to the number of elements in the mylink[] array. You do this by using the value stored automatically by the MakeArray() constructor in mylinks[0]. This element contains the number of elements in the array.

You should also have noticed that all the if tests from the earlier task have been removed, and a single return mylinks[ linkselect ] statement has been put in their place. This statement causes the value assigned to the element referenced by mylinks[ linkselect ] to be returned, linkselect being a random number between 1 and the value of linknumber.

It is important to note that you can consolidate the picklink() function even further by removing all the work variables and simply performing all the math inside the return statement, as shown here:

function picklink() {

   return mylinks[ ( Math.round( ( mylinks[0] - 1) * Math.random() ) + 1 ) ] ;

}

To add new links to your list, simply increase the value assigned by new MakeArray( value ), and add the new links to the list following the array elements already defined.

Finally, incorporate all these changes into the document created in the earlier task, remembering to include the MakeArray() constructor function. If you are a little lost at this stage, you can use the following completed HTML document as a guide:

<HTML>

<HEAD>

<TITLE>Random Link Generator with an Array</TITLE>

<SCRIPT LANGUAGE="JavaScript">

<!-- the contents of the script need to be hidden from other browsers

mylinks = new MakeArray( 5 );

mylinks[1] = "http://www.netscape.com/" ;

mylinks[2] = "http://www.webcom.com/taketwo/" ;

mylinks[3] = "http://java.sun.com/" ;

mylinks[4] = "http://www.realaudio.com/" ;

mylinks[5] = "http://www.worlds.com/" ;

function picklink() {

   return mylinks[ ( Math.round( ( mylinks[0] - 1) * Math.random() ) + 1 ) ] ;

}

function MakeArray( n ) {

// Initial concept Brenden Eich - Netscape Communications

   this.length = n;

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

       { this[i] = 0 }

   return this ;

   }

// End of script -->

</SCRIPT>

<BODY>

<H1>My random link generator</H1>

Click <A HREF="dummy.html" onClick="this.href=picklink()">here</A>

 to visit a randomly selected site from my list of favorites.

</BODY>

Task: Creating a Web Tour Guide

One of the more interesting possibilities offered by JavaScript is introduced through its capability to programmatically control the contents of a frame or frames. In the following task, you will learn how to use this capability to create a Web tour guide like the one shown in Figure 13.7.


Figure 13.7. JavaScript can be used to control the presentation of pages inside a frame or frames.

The top frame of Figure 13.7 contains a set of buttons that enable people to take a guided tour of the World Wide Web by clicking the displayed navigation buttons. Whenever a navigation button is clicked, a new Web page is displayed in the frame at the bottom of the screen. At the same time, a description of the page currently being viewed is constantly displayed in the text box on the right of the screen, with a second text box below it showing the next destination on the tour.

To Create the Tour Frameset

Before examining the JavaScript code, you need to create a frameset document to describe the layout of the frames. Name this document tourframe.html, and add the following HTML code to it:

<HTML>

<HEAD>

<TITLE>Web Tours Unlimited</TITLE>

</HEAD>

<FRAMESET ROWS="20%, *">

<FRAME SRC="tourscript.html" NAME="tourtop">

<FRAME SRC="tourstart.html" NAME="tourbottom">

</FRAMESET>

To Create the tourstart.html Document

When the Web tour first starts, the frameset needs to display a default page in the bottom frame. Create another new document and name it tourstart.html. In this document, include the following text:

<HTML>

<HEAD>

<TITLE>Web Tours Unlimited</TITLE>

</HEAD>

<BODY>

<P><I>This tour is best viewed by first turning off your Web browser's

Toolbar and Location or Document URL line. </I></P>

Click start to begin the tour...

</BODY>

If you had not wanted to display any information in the bottom frame, you could have made use of a special protocol in the <FRAME> tag called about:blank. In this case the frame definition would have looked like this:

<FRAME SRC="about:blank" NAME="tourbottom">

This tells Navigator 2.0 to display a blank page.

To Create the Form Details

The top frame of the frameset contains the tourscript.html document that looks after all the magic that makes the Web Tour work. Before looking at the JavaScript itself, you'll create the table and form layout. To start, enter this basic HTML structural code:

<HTML>

<HEAD>

<TITLE> Web Tours Unlimited</TITLE>

</HEAD>

<BODY

BACKGROUND="http://home.netscape.com/assist/net_sites/bg/paper/peach_paper.gif"

BGCOLOR="PINK" >

Next, you need to define the <FORM> tag and <TABLE> definition that holds all the buttons and fields for the tour navigator. The table consists of five columns on two rows, and on the top row the first cell spans four columns. In addition, the form is assigned the name tourform by using the NAME attribute. Here is the basic structure for such a table:

<FORM NAME="tourform">

<TABLE WIDTH="100%" BORDER="3">

<TR> <!-- Start of row one -->

  <TD ALIGN="CENTER" COLSPAN=4> <BR> </TD>

  <TD ALIGN="RIGHT"> <BR> </TD>

</TR>

<TR ALIGN="CENTER">  <!-- Start of row two -->

  <TD WIDTH="10%"> <BR> </TD>

  <TD WIDTH="10%"> <BR> </TD>

  <TD WIDTH="10%"> <BR> </TD>

  <TD WIDTH="10%"> <BR> </TD>

  <TD ALIGN="RIGHT" WIDTH="*"> <BR> </TR>

</TABLE>

</FORM>

</BODY>

After you have defined and tested this basic layout—remembering to test it within the frameset as well— you are ready to add the buttons and other elements of the form, as shown here:

<FORM NAME="tourform">

<TABLE WIDTH="100%" BORDER="3">

<TR> <!-- Start of row one -->

  <TD ALIGN="CENTER"COLSPAN=4> <FONT SIZE=5>Web Tours Unlimited</FONT> </TD>

  <TD ALIGN="RIGHT">Current Page:

  <INPUT TYPE="text" NAME="currenturl" VALUE="Start Tour" SIZE=35></TD>

</TR>

<TR ALIGN="CENTER">  <!-- Start of row two -->

  <TD WIDTH="10%"><INPUT TYPE="button" VALUE="  Start  " onClick="firstlink()">

  </TD>

  <TD WIDTH="10%"><INPUT TYPE="button" VALUE="Previous" onClick="prevlink()">

  </TD>

  <TD WIDTH="10%"><INPUT TYPE="button" VALUE="  Next  " onClick="nextlink()">

  </TD>

  <TD WIDTH="10%"><INPUT TYPE="button" VALUE="  Last  " onClick="lastlink()">

  </TD>

  <TD ALIGN="RIGHT" WIDTH="*">Next Page:

  <INPUT TYPE="text" NAME="nexturl" VALUE="Start Tour" SIZE=35>

  </TR>

</TABLE>

</FORM>

</BODY>

At this stage, the only difference between this form and any of the other forms you have encountered previously is the addition of onClick handlers for each of the buttons. The button labeled Start calls a function named firstlink(). The one labeled Previous calls the prevlink() function. The nextlink() function is assigned to the button labeled Next. And finally, the button labeled Last calls the function lastlink().

To Write the Script

With the <FORM> and <TABLE> blocks defined and tested, we'll return to the <HEAD> block and the <SCRIPT> definition. The first part of the script is very similar to the random links script in the earlier task called "A Random Link Generator Using an Event Handler." An array called mylinks[] is first defined with five elements, but this time, an additional array called mylinksnote[] is also declared with five elements, as shown here:

<SCRIPT LANGUAGE="JavaScript">

<!-- the contents of the script need to be hidden from other browsers

mylinks = new MakeArray(5);

mylinksnote = new MakeArray(5);

After the two arrays have been declared, they are loaded with a URL and corresponding description like the ones shown next. You can include your own links or use these for now. In addition, you can include extra links by increasing the value assigned in the new MakeArray( value ) statement.

mylinks[1] = "http://www.netscape.com/" ;

mylinksnote[1] = "Netscape Communications" ;

mylinks[2] = "http://www.webcom.com/taketwo/" ;

mylinksnote[2] = "Take TWO home Page" ;

mylinks[3] = "http://www.worlds.net/" ;

mylinksnote[3] = "Worlds Inc: The home of Alpha World" ;

mylinks[4] = "http://java.sun.com/" ;

mylinksnote[4] = "The Java Home Page" ;

mylinks[5] = "http://www.realaudio.com/" ;

mylinksnote[5] = "RealAudio Home Page" ;

Finally, after all the URLs and descriptions have been defined, you need to declare a global work variable called currentlink. This variable will be used to keep track of the current location of the Web tour. You declare this variable by writing this:

var currentlink = 0;

To Create the Navigation Functions

When you click any of the navigation buttons, its onClick handler calls a corresponding function.

The first of these functions is firstlink(). When firstlink() is called, the value of currentlink is set to 1, and a function named updatepage() is called. The code for the firstlink() function is as follows:

function firstlink() {

   currentlink = 1;

   updatepage() ;

}

As you will learn soon, updatepage() is what looks after the loading of each new page into the bottom form. It also ensures that the correct notes are displayed in the Current Page and Next Page fields.

When the prevlink() function is called, the value of currentlink is decremented by one and a check is made to see whether the start of the tour has been reached. If this is the case, an alert message is displayed; otherwise, the updatepage() function is called to display the previous page of the tour.

The code required to perform these functions is shown here:

function prevlink() {

   if ( --currentlink < 1 ) {

      currentlink = 1 ;

      alert("Already at start of tour")

      }

   else {

        updatepage() ;

   }

}

When the nextlink() function is called, the value of currentlink is incremented by one, and a check is made to see whether the end of the tour has been reached. If this is the case, an alert message is displayed; otherwise, the updatepage() function is called to display the next page of the tour.

The code required to perform these functions is shown here:

function nextlink() {

   if ( ++currentlink > mylinks[0] ) {

      currentlink = mylinks[0] ;

      alert("The tour is over")

   }

   else {

       updatepage() ;

   }

}

When the lastlink() function is called, the value of currentlink is set equal to the value of mylinks[0], and then the updatepage() function is called to display the last page of the tour.

The code required to perform these functions is shown here:

function lastlink() {

   currentlink = mylinks[0] ;

   updatepage() ;

}

To Use the updatepage() Function

As mentioned previously, the updatepage() function actually looks after the task of updating the contents of the bottom frame. It does this by setting the location property of the bottom frame. The location property contains the URL of the current document, displayed in either a frame or a main Web browser window. By altering the contents of this property, a new URL can be assigned to a frame or Web browser window. Doing so causes a new Web document to be loaded in place of the current one.

The location property of a frame can be addressed by the statement parent.frames[0].location, which indicates the location property of the first frame of the current Web window, and parent.frames[1].location the location property of second frame. Alternatively, you can also address a frame using the name assigned to it using the NAME attribute of its <FRAME> tag, which in the case of the bottom frame in this example is tourbottom. As a result, the bottom frame's location property can also be addressed by using parent.tourbottom.location.

Therefore, to change the contents of the bottom frame to the URL pointed to by mylinks[ currentlink ], you need to do only this:

function updatepage() {

   parent.tourbottom.location = mylinks[ currentlink ] ;

or alternatively this:

function updatepage() {

   parent.frames[1].location = mylinks[ currentlink ] ;

The updatepage() function also updates the contents of the currenturl and nexturl text fields by explicitly addressing them. You can access the contents of any field in a form by using the following:

document.forms[0].fieldname.value

where fieldname is replaced by the name of the field as defined by the forms <INPUT> tags, and forms[0] is the first form of the current Web document. As a result, the contents of the currenturl and nexturl text fields can be found by using document.forms[0].currenturl.value and document.forms[0].nexturl.value, respectively.

Alternatively, you can make use of the name assigned to the form by its NAME attribute, as discussed previously. In this case, you could use document.tourform.currenturl.value and document.tourform.nexturl.value.

Using this information, the code required to maintain the correct values for the currenturl and nexturl text fields is shown here:

   document.tourform.currenturl.value = mylinksnote[ currentlink] ;

   if (currentlink == mylinks[ 0 ] {

      document.tourform.nexturl.value = "Tour End"

      }

   else {

      document.tourform.nexturl.value = mylinksnote[ currentlink + 1 ]

   }

The Completed tourscript.html Document

To complete this part of the task, listed after the Note is the full text of the tourscript.html document, with the MakeArray() function added to permit the creation of mylinks[] and mylinksnote[]:


If you want to experiment with the Web Tour but don't want to key in all the code yourself, you can find an operation version at