Полезная информация


Special Edition Using HTML 4

Previous chapterNext chapterContents


- 16 -
Adding JavaScript and VBScript to HTML

by Jerry Honeycutt

Introducing Scripts

Scripts are important to an HTML author. I'm of the strong opinion that in the future you'll focus more on writing scripts than HTML tags. Whereas to create a document's content you'll use an HTML editor, which works like any popular desktop publishing program, you'll write scripts to make those documents interactive. Think of it this way: You use a word-processor to create documents, but you still must write the occasional macro to make a document interactive or solve special problems.

You're not going to learn how to write good scripts after reading this one chapter. Though it is a good basic introduction to scripting, particularly to the mechanics of adding scripts to HTML, you can't rely on it to teach you how to program. For that, take a look at Que's Special Edition Using JavaScript or Special Edition Using VBScript. If you're already familiar with the basic programming concepts, however, you can rely on Appendixes C, "JavaScript Keyword Reference," and D, "VBScript Keyword Reference," to show you all of the keywords supported by both scripting languages.

Choosing Between Server- or Client-Side Scripts

Server-side (see Part VI, "Scripting on the Web Server") scripts execute on the Web server, feeding HTML to the browser as a product of their computations. Write a server-side script for each circumstance if any of the following statements is true:


NOTE: Writing a server-side script isn't always possible, particularly if the service hosting your Web pages doesn't support server-side scripts. In such cases, you have no choice but to write a client-side script or relocate your Web pages to a service that does support scripts.

Client-side scripts interact with the HTML while the user is viewing it. Write a client-side script if any of these statements is true:

Choosing Between JavaScript and VBScript

JavaScript is loosely based on C++ and has gained worldwide acceptance on the Internet. You can use JavaScript to interact with the user's environment, change the appearance of the content while the user interacts with it, and even make embedded objects cooperate with each other. Both Netscape Navigator and Internet Explorer support JavaScript.

VBScript is based on Microsoft's Visual Basic. You also use it to create client-side scripts that interact with the user's environment, change content dynamically, and glue together objects. VBScript's biggest advantage is that you can leverage your existing knowledge about Visual Basic onto the Web page. Currently, Internet Explorer is the only Web browser that supports VBScript directly--a pretty big weakness.

When choosing between each of these languages, consider the following criteria for making your decision:


TIP: You can mix both JavaScript and VBScript within the same HTML file, so you're not forced to make a black-or-white decision. Do remember that Internet Explorer is the only browser supporting VBScript at this time.

Understanding How Browsers Interpret Scripts

JavaScript and VBScript are interpreted languages as opposed to compiled languages. Developers create programs using a compiled language such as C++. A compiler actually translates each instruction into machine code that the computer executes directly. A program called an interpreter interprets and executes a script line by line, however.

An interpreted language is slower than a compiled language, but, considering the usage of an interpreted language, that's not really an issue. Your scripts are interpreted by the Web browser and are usually very small. As well, they probably only execute in response to something that the user does (clicking the mouse), instead of executing continuously as compiled programs sometimes do.

When a Browser Executes Scripts

When a user opens a Web page, the browser makes note of every script in the HTML document. It translates the scripts into intermediate code that represents the keywords in the script as tokens (binary values representing the keywords), which are more efficient to interpret because they're smaller than the original keywords. It also creates a table called a symbol table that contains the name of each script function (scripts that are called by name from other scripts). The browser looks up functions in this symbol table as they are invoked.

The user's Web browser executes different types of script code at different times. The browser typically doesn't execute functions as the Web page loads; it waits for an event that you associate with a function to execute them instead. When an object on the Web page fires an event, the browser looks up the function associated with that event in the symbol table; then the browser executes it. Also, anytime a script invokes a function, the browser looks it up in the symbol table to find the code. The browser executes inline scripts as it loads the Web page, however. Inline scripts are code you embed that's not actually inside a function. You use inline scripts to affect how the browser draws the Web page.

In Listing 16.1, for example, the last line in the script executes as the browser loads the Web page, which creates the Web page shown in Figure 16.1. The remaining lines don't execute until some event causes the function called AddSeries to execute.

Listing 16.1  Sample Script

function AddSeries( Last )
{
  intTotal = 0;
  for( i = 1; i <= Last; i++ )
  {
    intTotal += i;
    alert( intTotal );
  }
}
document.write( "Howdy" );

How a Browser Handles Events

With scripting, you embed instructions into your Web pages that describe how you want the browser to handle certain events. Events are things that happen on the Web page. Mouse actions such as clicking and moving cause most events, but many other types of events can occur on a Web page such as a timer finishing its countdown. Regardless, most events are caused by some action.

Figure 16.2 illustrates this event-driven concept. Figure 16.2 has three key parts: an object, the event itself, and the event handler. The following list describes the three parts:

FIG. 16.1
document.write writes content to the Web page as the browser loads the HTML file.

FIG. 16.2
Events signal to the browser that an object on the Web page needs attention by a script. The browser determines which function to use.


Benefits of Event-Driven Programming
Events have many benefits over the old style of programming. The biggest benefit is the fact that you stay in control of the computer. Here are the highlights:


Learning to Program: Writing Scripts

You can write scripts in two ways. The first way is by using a wizard such as the Scripting Wizard that comes with Microsoft FrontPage and FrontPage Express. These wizards allow you to write very simple scripts and associate them with events and objects using a intuitive mouse-driven interface. If you're interested in approaching scripts this way, you don't need to learn how to program. You can learn more about using Microsoft's Scripting Wizard in "Writing Scripts with the ActiveX Control Pad," later in this chapter.

You can also write scripts the old-fashioned way: using a text editor. Doing so requires that you have an intimate understanding of the script language you're using. You can type your scripts directly into a file using your HTML editor, or you can type them into a plain text file that you link to your HTML file. You need to understand a few concepts about programming before you start writing scripts, however. If you already have basic programming skills, you can skip the rest of this section. If not, you need a quick overview of programming concepts such as variables and expressions.

Variables

Variables are names for a small chunk of memory in which you store a value. Variables can store a number or any bit of text. You don't need to worry about where in the computer's memory the script stores the variable's value because you use the variable's name to change or read its value.

Mathematical Expressions

Mathematical expressions return the result of a calculation. Two things make up a mathematical expression: operands (numbers, strings, or variables) and operators. When you add two numbers using a calculator, the numbers are the operands, and the plus sign (+) is the operator. Likewise, the minus (-), multiplication (*), and division signs (/) are operators. In most cases, you assign the result of a mathematical expression to a variable so that you can recall the result later. Examples of mathematical expressions written in JavaScript include the following:

8 + 4 Adds 8 and 4, returning 12 as a result.
2 * 3 + 1 Multiplies 2 by 3 and adds 1, returning 7 as a result.
3 + 2 * 5 Multiplies 2 by 5 because the multiplication operator has a higher order of precedence and adds 3, returning 13 as a result.
(3 + 2) * 5 Adds 3 to 2 because they're grouped together in parentheses and multiplies by 5, returning 25 as a result.
x = 1 + 2 Adds 1 and 2, storing the results in a variable called x.
x = y + 2 Adds 2 to the value stored in y and assigns the result to a variable called x.


NOTE: An operator's level of precedence determines the order in which the interpreter evaluates each operator in an expression. A multiplication operator has a higher order of precedence than an addition operator, so the interpreter evaluates the multiplication operator first.

The exception to this rule is when you put a portion of the expression inside parentheses. The interpreter evaluates anything you place inside parentheses before it evaluates the rest of the expression. If you have one set of parentheses with another, the interpreter evaluates the innermost set before evaluating the outermost set.


Boolean Expressions

Boolean expressions let you make decisions. They always evaluate to one of two values: True or False. You can assign the result of a Boolean expression to a variable, use it to control a loop, or use it to make a decision.

A simple Boolean expression contains any two values combined with a Boolean operator. Comparison operators are the heart and soul of Boolean expressions. You use them to determine the relationship between two values (greater-than, less-than, equal, and so on) and return True if the comparison is true or False if the comparison is false. For example, 1 < 2 returns True because one is less than two. On the other hand, 1 > 2 returns False because one is not greater than 2. Table 16.1 describes the most common comparison operators.

Table 16.1  Comparison Operators

Symbol Description Syntax
= Equality Expression1 = Expression2
<> (!=) Inequality Expression1 <> Expression2
< Less than Expression1 < Expression2
> Greater than Expression1 > Expression2
<= Less than or equal Expression1 <= Expression2
>= Greater than or equal Expression1 >= Expression2

The following are some examples that use comparison operators:
2 < 3 The result is True because 2 is indeed less than 3.
4 > 5 The result is False because 4 is not greater than 5.
4 <= 4 The result is True because 4 is less than or equal to 4.
x < 10 The result is True if x is any value less than 10; otherwise, the result is False.
y = x The result is True if y and x contain the same value; otherwise, the result is False.

Logical operators let you combine multiple comparison operators in a single expression. They're very simple to use; you plug in a couple of values and get a predictable result in return. For example, A And B is always True if both values are True. It's always False if either value is False. The following list describes the most important logical operators that JavaScript and VBScript support:

Not The Not operator negates a Boolean value. Not True returns False, for example, and Not False returns True.
And The And operator compares two Boolean values and returns True if both values are True. Otherwise, it returns False. Table 16.2 shows you the result for each combination of Boolean1 and Boolean2.

Table 16.2  And Operator

Boolean1 Boolean2 Result
True True True
True False False
False True False
False False False

Or The Or operator compares two Boolean values and returns True if either value is True. Otherwise, it returns False. Table 16.3 shows you the result for each combination of Boolean1 and Boolean2.

Table 16.3  Or Operator

Boolean1 Boolean2 Result
True True True
True False True
False True True
False False False

Xor The Xor operator compares two Boolean values and returns True if both values are different. Otherwise, it returns False. Table 16.4 shows you the result for each combination of Boolean1 and Boolean2.

Table 16.4  Xor Operator

Boolean1 Boolean2 Result
True True False
True False True
False True True
False False False

The following are some examples of Boolean expressions that rely on logical operators:
2 < 3 And 4 > 5 Returns False because this expression evaluates to True And False.
1 > 0 And 4 < 5 Returns True because this expression evaluates to True And True.
2 < 3 Or 4 > 5 Returns True because this expression evaluates to True Or False.
x < 0 And y > 0 Returns True if x is negative and y is positive.
x Or y Returns True if either variable contains a True value.

Decisions

VBScript and JavaScript contain a variety of statements you can use to control how your script flows. The syntax is different in each language, but both languages have roughly the same form.

The most basic type of decision making statement you'll use is the If...Then...Else statement. This statement evaluates a decision and conditionally executes a block of statements depending on the result. The statement has many different forms, but in general it looks like this:

If Condition Then
    Statements
Else
    Statements
End If

The first line is the heart of the If...Then...Else statement. It begins with the keyword If and ends with the keyword Then. Condition, the middle part, is the criteria. This is a Boolean expression that evaluates to either True or False. You learned to write Boolean expressions earlier in this chapter. If the condition is True, the script executes the first block of statements; otherwise, the script executes the second block of statements.

The following example shows you an If...Then..Else statement written in JavaScript. The condition is x < 3. If that condition is True, the interpreter executes the first alert statement. If that condition is False, the interpreter executes the second alert statement.

if( x < 3 )
  alert( "x was less than 3" );
else
  alert( "x was equal to 3 or greater" );

Loops

You can write a script that repeatedly executes the same statements until some condition is met or, alternatively, until some condition is not met. This is called looping. The primary reason to write a loop is so that you don't have to repeat a bunch of statements, like this:

Add the first number to sum
Add the second number to sum
Add the third number to sum
Add the fourth number to sum
Add the fifth number to sum

You can put these statements in a loop, instead, and let the script repeat them for you:

repeat the following line five times
  assign the next number to sum

Both VBScript and JavaScript support a variety of looping mechanisms, each with its own syntax. In general, though, a loop looks like this:

Loop Condition
    Statements

Statements is called the body of the loop. The interpreter iterates the loop over and over until Condition becomes True. Each time the interpreter does so, it executes the statements in the body of the loop.

The following example shows you a while loop in JavaScript. As long as i is less than 10, the interpreter executes the two statements contained in the body of the loop. The first statement simply displays the current value of i. The second statement adds 1 to i. The number of times that this loop executes depends entirely on the value of i as the interpreter enters the loop; if i started at 0, the loop executes 10 times.

while( i < 10 )
{
  alert( i );
  i = i + 1;
}

Functions

Functions (and subprocedures in VBScript) let you divide your scripts into chunks you call from any other script. Invoking a function in your script is called calling a function. You give a function a name and a list of arguments. You call the function by its name and pass arguments by their position. In general, a function looks like this:

Name( Arguments )
    Statements
End

Name is the name of the function, which you use to invoke the function from a script or associate the function with an object's event. Arguments is a list of parameters that you pass to the function as variables. Statements is all the code you want the interpreter to execute each time it invokes the function. A function can also return a value to the calling script; thus, you can use a function on the right side of an equal sign, like this:

Result = MyFunction( Variable1, Variable2 )

The whole process works as follows:

1. You call a function by name to invoke it, passing any values on which you want it to operate as arguments.

2. The interpreter executes the function, setting each variable in the argument list to the values you passed.

3. When the function finishes, it specifies a return value to the interpreter, which returns the result in the expression that invoked the function.

Adding Scripts to Your HTML File

You embed scripts in an HTML file using tags, much like any other content you put in a Web page. Scripts are put between the <SCRIPT> and </SCRIPT> container tags, as shown in Listing 16.2. You specify the language you're using by assigning the MIME type of the language to the TYPE attribute: text/vbscript for VBScript or text/javascript for JavaScript.

Listing 16.2  A Sample Script

<SCRIPT TYPE="text/vbscript">
<!--
    ` The following line is executed when the page is loaded
     Alert "Howdy from Texas"
    ` The following function is executed online when invoked
    Sub Pause
        MsgBox "Click on OK to Continue"
    End Sub
` -->
</SCRIPT>

When your browser loads a Web page that includes scripts (parse time), it immediately evaluates each <SCRIPT> block it encounters. The browser grabs everything in a <SCRIPT> block and passes the content off to the scripting engine. The scripting engine looks at the <SCRIPT> block the browser gave it and looks for any functions and global variables (variables outside a function). The scripting engine compiles the functions and global variables and stashes their names in the symbol table for later use. The scripting engine immediately executes statements it finds outside a function, though. This is called immediate execution. Scripts that the browser executes immediately are called inline scripts.


NOTE: Prior to HTML 4.0, you might have used the LANGUAGE attribute to specify the scripting language you're using. W3C encourages you to use TYPE instead of the LANGUAGE attribute because its values are not standardized. Note that Internet Explorer and Navigator don't support the TYPE attribute as of this writing. Until both browsers do, you can safely use the LANGUAGE attribute to specify the scripting language by assigning either JAVASCRIPT or VBSCRIPT to it, like this:
<SCRIPT LANGUAGE=JAVASCRIPT>
<SCRIPT LANGUAGE=VBSCRIPT>

Specifying a Default Scripting Language

You can specify a default scripting language for an HTML file and forget about specifying it within each <SCRIPT> tag. You use the <META> tag at the beginning of your HTML file. Set HTTP-EQUIV to Content-Script-Type and set CONTENT to the MIME type of the scripting language you're using. The following example sets the default language for the HTML document to JavaScript:

<META http-equiv="Content-Script-Type" content="text/javascript">

You can also set the default scripting language using an HTTP header as shown in this example for VBScript:

Content-Script-Type: text/vbscript


CAUTION: Failing to specify the scripting language you're using is not only incorrect but also can cause problems for you in the future. Either define your choice globally or within each <SCRIPT> tag, but don't rely on the browser's default scripting language to always be JavaScript or VBScript.

Linking to Scripts Instead of Embedding Them

You can link to a script that's stored in a separate text file instead of embedding the script into the HTML document. To do so, assign the URL of the file containing your scripts to the <SCRIPT> tag's SRC attribute:

<SCRIPT SRC=script.vbs TYPE="text/vbscript">

Because you must still specify the language using the TYPE attribute, you can use only a single language within each text file. To help identify the types of scripts stored in each file, use an appropriate file extension. Consider using the following conventions:

Hiding Scripts from Older Browsers

Many browsers can't interpret scripts. When one such browser encounters a script, it ignores the <SCRIPT> and </SCRIPT> tags because it doesn't know how to interpret them (this behavior is by design). Then the browser displays everything between those two tags as content, which is not exactly what you had in mind. Figure 16.3 shows an example of what this looks like.

FIG. 16.3
You can see this example for yourself by mistyping SCRIPT in the <SCRIPT> tag and opening the Web page in Navigator or Internet Explorer.

You use an HTML comment to hide scripts from browsers that don't support scripting, however. Make the opening HTML comment the first line within the script. The closing HTML comment should be the last line in the script block. Note that when using JavaScript you begin this line with a JavaScript comment (//) because after JavaScript starts interpreting code, it thinks that everything else in the script is actual JavaScript code. VBScript users begin the same line with a VBScript comment (`). Script-enabled browsers ignore the comments and interpret the scripts, whereas other browsers ignore all the content between the comments. Listing 16.3 shows you a JavaScript example.

Listing 16.3  Hiding Scripts

<SCRIPT TYPE="text/javascript">
<!--
  function AddSeries( Last )
  {
    intTotal = 0;
    for( j = 1; j <= Last; j++ )
    {
      intTotal += j;
      alert( intTotal );
    }
    return intTotal;
  }
  document.write( "Howdy" );
//-->
</SCRIPT>

Associating Scripts with Events

Most objects on a Web page have events. That includes each HTML tag, control, or form element. Some events to which you attach scripts include those listed in Table 16.5.

Table 16.5  Events Defined in HTML 4.0

Name Event Is Raised When
OnLoad The browser finishes opening the HTML document.
OnUnload The browser unloads the HTML document.
OnClick The user clicks the mouse on an element.
OnDblClick The user double-clicks an element.
OnMouseDown The user presses the mouse button.
OnMouseOver The user moves the mouse over an element.
OnMouseMove The user moves the mouse over an element.
OnMouseOut The user moves the mouse out of an element.
OnFocus An element receives keyboard focus.
OnBlur An element loses keyboard focus.
OnKeyPress The user presses and releases a key.
OnKeyDown The user presses a key over an element.
OnKeyUp The user releases a key over an element.
OnSubmit A form is submitted to the Web server.
OnReset A form is reset.
OnSelect The user selects text in a text field.
OnChange An element loses focus and has changed.

Recall from Figure 16.2 that objects, events, and event handlers all work together. You have to associate an object with an event handler via that object's event. You do that by adding the event's attribute to the object's HTML tag and setting its value to a single statement that executes the function. For example, to associate a JavaScript function called MyFunction() with the onClick event of a button, you write the button's <INPUT> tag as follows:

<INPUT TYPE=BUTTON NAME=BUTTON onClick="MyFunction()">

You can just as easily associate an event handler with any other event in Table 16.5. In this case, the event attribute is onClick. Add another event attribute from the first column of Table 16.5 to the tag in the preceding example to associate an event handler with that event, like this:

<INPUT TYPE=BUTTON NAME=BUTTON onClick="MyFunction()" MouseOut="ByeMouse()">

You can also use the FOR and EVENT attributes, which let you associate a script with any named object in the HTML file and any event for that object. Take a look at the following:

<SCRIPT FOR="Button" EVENT="Click" TYPE="text/javascript">
<!--
 window.alert( "Ouch! You clicked on me." )
-->
</SCRIPT>
<INPUT TYPE=BUTTON NAME=Button>

This defines a button (with a NAME of Button) that executes the script when the user clicks it. The <SCRIPT> tag contains the FOR and EVENT attributes that define the object and event associated with that script. FOR="Button" EVENT="Click" says that when an object named Button triggers the Click event, every statement in this script is executed.

Writing Scripts with the ActiveX Control Pad

There is certainly a better way to add scripts to your HTML documents. The ActiveX Control Pad is a free product from Microsoft that makes short work of this. You get it through Microsoft's Site Builder Workshop at http://www.microsoft.com/workshop/author/cpad. Figure 16.4 shows you the Control Pad's HTML editor with an HTML file in it.


TIP: The Control Pad uses VBScript by default. If you want to use JavaScript, you need to set it to do so. Choose Tools, Options, Script from the main menu and select JavaScript. The Script Wizard now generates JavaScript language scripts rather than VBScript.

The Script Wizard provides two different ways you can edit scripts: List view and Code view. List view is a bit easier to use. Click the Script Wizard button in the toolbar to open the Script Wizard. Then click the List View button at the bottom of the window. See the window shown in Figure 16.5.

FIG. 16.4
The Editor window shows you only the contents of your HTML. Save the file to disk and open it in your Web browser to preview what the Web page looks like.

FIG. 16.5
In most cases, the List view is all you ever need to create exciting Web pages.

You associate an object's event with another object's methods and properties. Select an event on the left pane of the wizard. Choose a method or property in the right pane. When you click the Insert Action button, the Script Wizard prompts you for the value of the property or for any parameters you want to pass to a method. You can rearrange the order of the actions in the bottom pane of the Script Wizard. Close the Script Wizard, and it'll add your script to the HTML file.

If you're more comfortable with the traditional programmer view of life, use the Script Wizard's Code view (see Figure 16.6). This works just like the List view, except that you don't see a list of associated events and actions in the bottom pane. You see the actual code the Script Wizard creates instead. Click the Script Wizard button in the toolbar to open the Script Wizard. Then click the Code View button at the bottom of the window, add your script, and close the Script Wizard.

FIG. 16.6
You must use Code view if you want to use compound statements such as If in your scripts.


TIP: Keep your Web browser running with the Web page on which you're working in it. Then you can save the changes, flip to the browser, and refresh the Web page to see your changes while you're working in Control Pad.

Using Scripts from Other People

The quickest way to add scripts to your Web page is by using a script that you download from a gallery or library. For example, the Template Studio (http://tstudio.usa.net) is a comprehensive gallery that contains numerous scripts you can use in your Web page. The scripts you find on this site include scripts for detecting the user's browser, dynamically replacing an image, controlling a window, displaying messages, and setting cookies.

Gamelan (http://javascript.developer.com) also has a comprehensive site that you can use to find good scripts for your Web page. Tutorial examples, games, and other miscellaneous scripts are featured on this Web site. You can use modify them to suite your own purposes and use them to learn more about scripting. As a bonus, you'll find documentation that helps a new JavaScript developer get up-to-speed fast.

If you want even more immediate gratification, however, you can try out the scripts described in the following sections. These scripts help you add fly-over help for the links on your Web page.


TIP: Netscape provides more than a dozen, real-world example JavaScript Web pages that you can use. Open http://developer.netscape.com/library/examples/examples.html#javascript in your Web page.

Fly-Over Help for a Link's Destination

Take a look at Communicator's status line when you hold the mouse pointer over a link. It shows the URL to which the link points. You can provide a more useful description of the link's destination by using a script (see Figure 16.7).

FIG. 16.7
Providing a more thorough description of a link can prevent the user from visiting Web pages in which she isn't interested. Thus, you're saving Internet bandwidth.

You use the <A> tag's onMouseOver event to display the help text and its onMouseOut event to remove the text. For every link on your Web page, add the following onMouseOver attribute to its <A> tag. Each time the user moves the mouse over the link's anchor, the two statements assigned to this event execute. The first statement, self-status='The help text'; displays the text contained within the single quotes on the browser's status line. Change this text to a brief description of the link. The following shows the second statement, return true;, which prevents the browser from displaying the link's URL reference on the status line:

onMouseOver="self.status='The help text'; return true;"

Also add the onMouseOut event attribute to each <A> tag as you see in the following example. This works just like the onMouseOver attribute you just read about except that it clears the status line when the user moves the mouse out of the link. The effect is that the user sees the help text as long as she holds the mouse over the link; but when she moves the mouse away from the link, the status line clears.

onMouseOut="self.status=''; return true;"

Using Forms and JavaScript for Navigation

If you've visited Microsoft's site recently, you've seen forms used for navigation. Here's how it works: you select an item from the drop-down list and click a button. The browser opens the URL associated with that list item (see Figure 16.8).

FIG. 16.8
Alternatively, you can create a server-side script that processes the user's choice on the server. This approach is more efficient, however, because it's done on the client.

Listing 16.4 shows the HTML for a form with a single drop-down list. It opens the Web page that the user chooses from the list. The function OpenURL() is associated with the <SELECT> tag's OnChange event. When the user selects an item from the form's list, OpenURL() sets window.location to the associated URL.

Listing 16.4  Form and Script for Navigation

<HTML>
<SCRIPT LANGUAGE=JAVASCRIPT>
<!--
  function OpenURL( Index )
  {
    if( Index == 0 ) window.location = "http://rampages.onramp.net/~jerry";
    if( Index == 1 ) window.location = "http://www.microsoft.com";
    if( Index == 2 ) window.location = "http://www.mcp.com";
    if( Index == 3 ) window.location = "http://www.netscape.com";
  }
//-->
</SCRIPT>
<FORM NAME=NAVIGATE>
  <SELECT NAME=LIST SIZE=1 OnChange="OpenURL( document.NAVIGATE.LIST.selectedIndex )">
  <OPTION NAME=JERRY>Jerry's Homepage
  <OPTION NAME=MS>Microsoft
  <OPTION NAME=QUE>Macmillan Publishing
  <OPTION NAME=NETSCAPE>Netscape
  </SELECT>
</FORM>
</HTML>

To make this work in your Web page, you need to update the form's list to contain an entry for each Web site to which you want the user to navigate. Then you need to add a line to the OpenURL function that checks the index of the user's selection and opens the appropriate URL in the browser. The easiest thing to do is to copy one of the existing lines, change the index number so that it corresponds with the form, and then change the URL assigned to window.location. Just remember that the first item in the list has an index of 0, the second has an index of 1, and so on. 


Previous chapterNext chapterContents


© Copyright, Macmillan Computer Publishing. All rights reserved.