Chapter 20

Creating Interactive Web Pages with JavaScript


CONTENTS


JavaScript is a powerful scripting language for the World Wide Web. You can use it to create interactive Web pages and make a Web site easier and more interesting to navigate. Traditionally (over the past few years), Web site developers have relied on CGI to make Web sites interactive. Although it may work well in some cases, it is a waste of resources in other cases. If a user in Sweden makes a mistake when filling out a form at a Web site in the United States, for example, the user will not know about it until the entire form is filled in and submitted to the Web server via transcontinental network lines. After the form is submitted, the server performs a series of error checks, detects the mistake, and returns an error message to the user in Sweden. This process is clearly a waste of resources. It wastes Internet bandwidth and unnecessarily burdens the Web server because the error check could have been performed on the browser. This phenomenon is known as the thin client syndrome. Although Web browsers are increasingly becoming more and more sophisticated, resources of most computers used to browse the Web are underutilized. Using JavaScript, you can make use of these resources and create highly interactive Web sites.

The purpose of this chapter is not to provide you with a comprehensive overview of JavaScript. Such an overview is beyond the scope of this book. Refer to Teach Yourself JavaScript in One Week, published by Sams.net for additional information about JavaScript. The next few sections, however, do provide an overview of JavaScript and discuss how you can use it to make a Web site interactive and exciting to navigate. Before you get to the overview of JavaScript, the next section demonstrates how easy it is to create a simple application with JavaScript by showing you how to create the classic "Hello World" application.

In later sections, you learn various aspects of the JavaScript language and examine a few examples of simple JavaScript applications. Because you can find these examples on the CD-ROM, I recommend that you spend some time experimenting with them as you read this chapter. Several informative JavaScript resources on the Internet that you can use to obtain the most up-to-date information about JavaScript also are presented at the end of this chapter.

JavaScript "Hello World" Application

The "Hello World" application shown in Figure 20.1 was created with the following HTML code. This HTML code does not have the <SCRIPT> tag. Instead, as you can see in line 25, it uses a JavaScript event to invoke a JavaScript function and display a message box. The message box created by the alert function in line 25 is shown in Figure 20.2.

Figure 20.1: The JavaScript "Hello World" application.

Figure 20.2: The Message box created by the alert function when the command button in Figure 20.1 is clicked.

 1: <!--
 2:   (c)1996 Sanjaya Hettihewa (http://wonderland.dial.umd.edu)
 3:   All Rights Reserved.
 4:       Permission is hereby given to modify and distribute this code as you wish
 5:   provided that this block of text remains unchanged.
 6: !-->
 7:
 8: <HTML>
 9: <HEAD>
10: <TITLE>JavaScript Tutorial: Hello World!</TITLE>
11: </HEAD>
12:
13: <BODY BGCOLOR="#FFFFFF" TEXT="#0000FF"
14:       LINK="#B864FF" VLINK="#670000" ALINK="#FF0000">
15:
16: <IMG SRC="JavaScript.gif"><P>
17:
18: <B><FONT FACE="Comic Sans MS" SIZE=6 COLOR=RED>
19: JavaScript Tutorial: </FONT></B>
20: <I><FONT FACE="Comic Sans MS" SIZE=5 COLOR=BLUE>
21: "Hello World!" </I><P></FONT>
22:
23: <FORM>
24:
25: <INPUT onClick="alert('Hello World')"
26:  TYPE=BUTTON VALUE="Please click here for message box">
27:
28: </FORM>
29:
30: </BODY>
31:
32: </HTML>

Benefits of JavaScript

Using JavaScript, you can accomplish a variety of tasks at the client side without interacting with a Web server. The following sections list a few tasks that you can accomplish with JavaScript. You also can find various JavaScript examples presented in this chapter on the CD-ROM that accompanies this book in the directory Chapter-20. I recommend that you experiment with various JavaScript programs in the CD-ROM as you read about them.

Client-Side Data Validation

JavaScript is ideal for validating user input and making sure that data entered by users is valid. Prior to client-side scripting languages such as JavaScript, when a user filled in a form with information, it had to be sent to the server to be processed via a CGI script to validate user input. This process was time-consuming and a waste of network and Web server resources. A better way of handling this process would be to set up a JavaScript application to check user input before it is submitted to a Web server for processing.

Managing Browser Objects

You can easily manipulate various browser objects with JavaScript. When a user moves the mouse pointer over a hypertext link, for example, you can use JavaScript to display the URL's description on the status bar of the browser. Later in this chapter, you learn how easy it is to use JavaScript to display messages on the status bar of Web browsers.

Conserving Bandwidth

Although some people might argue that JavaScript-enhanced pages take up more bandwidth, this is not really the case if JavaScript is used intelligently to conserve bandwidth. Before invalid data in a form is sent to a Web server for processing, for example, JavaScript can validate the data.

Conserving Resources of the Web Server

JavaScript supports distributed processing by enabling various tasks to be performed on the client rather than on the server. Although you can perform various tasks using CGI programs, a client-side scripting language such as JavaScript is ideal for performing simple operations that do not require access to information on a remote server.

Basics of JavaScript

As shown in the following code listing, JavaScript code is enclosed in the two HTML tags <SCRIPT LANGUAGE="JavaScript"> and </SCRIPT>. Browsers that do not understand certain HTML tags sometimes display text defined between the two unknown tags as they appear. This is not desirable for JavaScript programs because it will most likely confuse users browsing a JavaScript-enhanced Web page with a Web browser that does not support JavaScript. As shown in lines 2 and 4 of the code listing, JavaScript code can be hidden from browsers that do not support it by commenting out JavaScript programs using the two HTML tags used to comment HTML code (<!-- and -->).

1: <SCRIPT LANGUAGE="JavaScript">
2: <!-- Hide JavaScript from technologically challenged Web browsers
3: … JavaScript Code …
4: // Hide JavaScript from technologically challenged Web browsers -->
5: </SCRIPT>

Defining all JavaScript code in the HEAD section of a Web page is recommended. This way, you can make sure that any JavaScript code that should be evaluated before users are given the chance to manipulate various objects of a Web page. For example, a Web page might have an input control whose default value is set by a JavaScript subroutine. This input control should be updated with an appropriate value before the user is given a chance to manipulate the input control.

JavaScript Data Type Values

JavaScript supports the manipulation of a number of data type values. Various types of data supported by JavaScript are listed next. These data types can be manipulated with operators and expressions covered in the next two sections.

Numbers such as 1234 and 123.456.
Boolean expressions such as true and false.
Literals such as 1234, 123.456, and "Hello".
Strings of characters such as "Windows NT". Note that strings and literals can be concatenated with the + operator.
Floating-point numbers such as 123, 123.456, -123.1E12, and .1e23.
Special character sequences such as \b for backspace, \n for new line character, \r for carriage return, and \t for tab character.
Escape characters such as \" used to represent the quoted character literally.

Useful JavaScript Operators

The operators presented next are supported by JavaScript to manipulate expressions and objects of various data types supported by JavaScript.

String Operators

Strings can be concatenated with the two operators + and +=. For example, "Windows " + "NT" returns the string "Windows NT". The += operator is handy for adding a string expression to a string variable. For example, if the string stringVariable contains the string "Windows ", stringVariable += "NT" results in the string "Windows NT" being assigned to stringVariable.

Comparison and Logical Operators

Expressions of similar data types can be compared with various comparison operators. If you use a string expression, comparison operators compare the two expressions based on the standard lexicographic ordering. After the comparison is performed, a Boolean expression is returned by the comparison operators shown in Table 20.1.

Table 20.1. Comparison operators.

Operator
Description
= =
If both operands are equal, true is returned.
!=
If both operands are not equal, true is returned.
>
If the left operand is greater than the right operand, true is returned.
>=
If the left operand is greater than or equal to the right operand, true is returned.
<
If the right operand is greater than the left operand, true is returned.
<=
If the right operand is greater than or equal to the left operand, true is returned.
&&
If both left and right operands evaluate to true, true is returned.
||
If either the left or right operand evaluates to true, true is returned.

Mathematical Operators

You can use the mathematical operators shown in Table 20.2 to evaluate various numerical expressions.

Table 20.2. Mathematical operators.

Operator
Description
+=
Adds left operand to right operand and assigns the result to the left operand.
-=
Subtracts left operand from the right operand and assigns the result to the left operand.
%=
Calculates the value of the left operand modulo right operand and assigns it to the left operand.
/=
Calculates the value of the left operand divided by the right operand and assigns it to the left operand.
++
Increments the operand.
--
Decrements the operand.
!
Negates the operand. (If operand is false, true is returned.)

JavaScript Expressions

The simplest JavaScript expression is <VariableName> = <expression> where the value of the <expression> is assigned to the <VariableName>. JavaScript also supports conditional expressions. You can use conditional expressions to selectively assign a value to a variable based on a certain condition according to the following syntax:

<Variable Name> = (<Boolean expression) ? "<value if expression is true>" : "<value if expression is false>"

JavaScript Events

Table 20.3 lists various events supported by JavaScript. Events are actions associated with various objects of a Web page. When a user clicks on a button, for example, the onClick event is triggered. JavaScript programs can respond to various user interactions by monitoring and responding to the various events listed in this table.

Table 20.3. JavaScript events.

JavaScript Event NameEvent Description
onBlur An object loses focus.
OnClick An object is clicked on.
OnChange The value of an input object is changed.
OnFocus An object receives focus.
OnLoad A Web page is loaded.
OnMouseOver The mouse pointer is moved over an object.
OnSelect The user selects the form element's input field.
OnSubmit A form is submitted.
OnUnload The user leaves the current Web page.

Sample JavaScript Applications

Creating JavaScript applications is easy after you grasp the basics of JavaScript. Before you create your own JavaScript applications, I recommend that you study the JavaScript language by visiting various JavaScript Internet resources given at the end of this chapter. It is also a good idea to experiment with the following JavaScript examples and study how various JavaScript functions, operators, and expressions are used.

Labeling URLs on the Status Bar

The following code listing demonstrates how you can use JavaScript to label hypertext links of a Web page. When the mouse pointer is moved over a Web page, its description is displayed on the Web browser's status bar. As shown in the following code listing, the JavaScript event onMouseOver is used to determine whether the mouse pointer is over a hypertext link. If it is, the window.status object is used to display a message on the Web browser's status bar. Note how the status bar of the Web browser shown in Figure 20.3 displays the message defined in line 26 of this code listing.

Figure 20.3: You can use JavaScript to label hypertext links of a Web page.

 1: <!--
 2:   (c)1996 Sanjaya Hettihewa (http://wonderland.dial.umd.edu)
 3:   All Rights Reserved.
 4:   Permission is hereby given to modify and distribute this code as
 5:   you wish provided that this block of text remains unchanged.
 6: !-->
 7:
 8: <HTML>
 9: <HEAD>
10: <TITLE>JavaScript Tutorial: Labeling URLs</TITLE>
11: </HEAD>
12: <BODY BGCOLOR="#FFFFFF" TEXT="#0000FF"
13:             LINK="#B864FF" VLINK="#670000" ALINK="#FF0000">
14:
15: <TABLE COLSPEC="L20 L20 L20" BORDER=2 WIDTH=100%>
16: <CAPTION ALIGN=top>Labeling URLs with JavaScript</CAPTION>
17: <TR><TD>
18: <IMG SRC="JavaScript.gif">
19: <TD>
20:
21: <TABLE BORDER=2 width=100%>
22: <CAPTION ALIGN=top>URLs</CAPTION>
23: <TR><TD>
24: <A HREF="http://www.microsoft.com/"
25:    onMouseOver="window.status=
26:    'Status bar description = Microsoft Web site';
27:    return true">URL # 01</A>
28: </TD><TD>
29: <A HREF="http://home.nestcape.com/"
30:    onMouseOver="window.status=
31:    'Status bar description = Netscape Web site';
32:    return true"">URL # 02</A>
33: </TD></TR>
34: <TR><TD>
35: <A HREF="http://www.mcp.com/"
36:    onMouseOver="window.status=
37:    'Status bar description = Macmillan Web site';
38:    return true"">URL # 03</A>
39: </TD><TD>
40: <A HREF="http://www.yahoo.com/"
41:    onMouseOver="window.status=
42:    'Status bar description = Yahoo Web site';
43:    return true"">URL # 04</A>
44: </TD></TR>
45: </TABLE>
46: </TR>
47: </TABLE>
48:
49: <B><FONT FACE="Comic Sans MS" SIZE=6 COLOR=RED>
50: JavaScript Tutorial: </FONT></B>
51: <I><FONT FACE="Comic Sans MS" SIZE=5 COLOR=BLUE>
52: Labeling URLs with JavaScript</I><P></FONT>
53:
54: </BODY>
55: </HTML>

Displaying the Last Modification Date of Web Pages

The last modified date of a Web page is often useful to users browsing a Web site-specifically, if the Web page contains time-sensitive information. Although you can add the time and date manually whenever a Web page is modified, doing so just adds an extra step to the Web page development process. You can automate this process by using a JavaScript program. The date and time of the last Web page modification shown in Figure 20.4 was generated with the following code listing. The line numbers are for reference purposes only, and are not part of the HTML code.

Figure 20.4: You can use JavaScript to automatically display the date and time a Web page was last modified.

 1: <!--
 2: (c)1996 Sanjaya Hettihewa (http://wonderland.dial.umd.edu)
 3: All Rights Reserved.
 4: Permission is hereby given to modify and distribute this code
 5: as you wish provided that this block of text remains unchanged.
 6: !-->
 7:
 8: <HTML>
 9: <HEAD>
10: <TITLE>JavaScript Tutorial: Displaying Date of Modification</TITLE>
11: </HEAD>
12:
13: <BODY BGCOLOR="#FFFFFF" TEXT="#0000FF"
14:             LINK="#B864FF" VLINK="#670000" ALINK="#FF0000">
15:
16: <TABLE COLSPEC="L20 L20 L20" BORDER=2>
17: <CAPTION ALIGN=top>Displaying Date of Modification</CAPTION>
18: <TR><TD>
19: <IMG SRC="JavaScript.gif">
20: </TD><TD>
21: This Web page was last modified on: <BR>
22: <SCRIPT LANGUAGE="JavaScript">
23:  lastModifiedDate = document.lastModified
24:  document.write(lastModifiedDate);
25: </SCRIPT>
26: </TD></TR></TABLE>
27:
28: <B><FONT FACE="Comic Sans MS" SIZE=6 COLOR=RED>
29: JavaScript Tutorial: </FONT></B>
30: <I><FONT FACE="Comic Sans MS" SIZE=5 COLOR=BLUE>
31: Dating Web pages</I><P></FONT>
32:
33: </BODY>
34:
35: </HTML>

JavaScript Resources on the Internet

Numerous JavaScript resources are available on the Internet. Visit the following URLs to obtain additional information about JavaScript. Because JavaScript is a relatively new and evolving language, you should visit the following Web sites for the most up-to-date information about the language and various innovative applications of it. A number of Web sites listed in the following sections also contain sample JavaScript applications that demonstrate various capabilities of the language.

Netscape's JavaScript Authoring Guide

Netscape's JavaScript authoring guide is a comprehensive source of information about JavaScript. Visit it to obtain extensive information about various JavaScript functions and language concepts.

URL
Netscape's JavaScript authoring guide:
http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/index.html

JavaScript Snippet Library

The JavaScript Snippet Library contains many useful JavaScript applications. Applications at this Web site are broken down into various sections. Visit the URL listed next to learn more about JavaScript and how you can use it to create interactive Web pages.

URL
JavaScript Snippet Library:
http://www.freqgrafx.com/411/library.html

Java Message Exchange

When you program with JavaScript, knowing various tips and tricks that can potentially save time and frustration is often valuable. A good way to avoid commonly made mistakes is to read about them.

URL
The Java Message Exchange Web site contains an index of questions and answers related to JavaScript:
http://porthos.phoenixat.com/~warreng/WWWBoard/wwwboard.html

JavaScript Color Center

The JavaScript Color Center is a good example of how you can use JavaScript to create sophisticated, multiframe applications.

URL
See the JavaScript Color Center Web site to learn more about JavaScript and to find RGB color codes:
http://www.hidaho.com/c3/

Summary

JavaScript is a powerful scripting language that you can use to combat the thin client syndrome and create interactive Web pages. Because JavaScript applications do not need to interact with a Web server, they are capable of validating information that users enter into various forms before it is sent to a Web browser for processing. This capability saves both resources of the Web server and also network bandwidth.

You also can use JavaScript to make a Web site easier to navigate by providing additional information to users browsing the site. When a user moves the mouse pointer over an HTML link, for example, JavaScript can display a message on the status bar of the Web browser and give more information about the link.

As you learned in various examples in this chapter, you can use JavaScript to make a Web site interactive and more interesting to navigate by making use of resources at the client side that are often underutilized. Using JavaScript and VBScript, which is covered in the following chapter, you can add a new level of interaction to a Web site without using CGI.

What's Next?

VBScript is similar to JavaScript in many ways. It was designed by Microsoft to make it easier for Web site developers to create compelling Web sites and incorporate various ActiveX controls to a Web page. You can use VBScript, which is a subset of Visual Basic, to create "Active" Web pages. In the next chapter, you get a thorough overview of VBScript and learn how you can create VBScript applications and add them to a Web page. To get you started with VBScript, you can use the several sample applications given in the chapter.