Chapter 34

Using JavaScript in Your Web Pages

by Rick Darnell


CONTENTS

JavaScript, a scripting extension to HTML, extends your ability to respond to user events without the need for client-server communication or CGI scripting.

In the past, a form typically was submitted to the server for all processing, whether it meant checking a ZIP code or putting information in a database. Each time information was passed back and forth between client and server, it slowed down the process, due to inherently slow communication lines. JavaScript eliminates much of the client-server communication by shifting responses to user events to the client side. Because network transmission is not required, the process goes much faster.

Getting to Know JavaScript

JavaScript is more closely related to a programming language than to HTML tags. JavaScript cannot exist, however, outside of HTML. To function, it must be included as part of a page.

JavaScript was developed by Netscape in conjunction with Sun's Java. You may also know it as LiveScript-the first name it had before the collaboration with Sun.

Javascript Isn't Java
Java is an object-oriented programming language used to create standalone applications and applets, special "mini" applications for Web pages. Writing Java programs is easiest when you have some background in programming, such as with C or C++.
Java is compiled into machine-independent bytecodes, which are in turn interpreted by the Java Virtual Machine on the host computer. The bytecodes are generic instructions, such as "print this line," or "create this variable," which are then given nitty-gritty detail by the interpreter on the host machine.
JavaScript shares some of the same syntax and structure as Java, but it provides a much smaller and simpler language for people with HTML or CGI experience. It gets interpreted along with the rest of the page at load time. JavaScript resides only within an HTML document and provides for greater levels of interactivity than basic HTML commands.
For example, JavaScript enables the HTML author to respond to user-initiated events, such as mouse clicks and form activity, without the need for client-server interaction. The result provides quicker operation for the end user and less load on the server.
Although similarities exist between Java and JavaScript, the languages are different and are intended for different uses. A simple form-handling routine that would require a significant amount of coding in Java represents a basic task for JavaScript, but creating a browser such as HotJava in JavaScript is impossible.
Java applets occupy a defined space on the screen, much as an image or other embedded item. Although an applet can communicate with another applet on the same page, communicating with a page's HTML elements requires a substantial amount of code.

JavaScript does not represent a watered-down version of Java for programming beginners. Although related to Java, it provides a solution for client-side scripting in an era when users with high-powered machines get bogged down by client-server communication.

Although many ways exist to control the browser from within a Java applet, simple tasks such as computing a form or controlling frame content become complicated affairs. JavaScript bridges the gap by enabling HTML authors to implement basic HTML functionality and interactivity without hours and hours of codewriting.

The other side of the coin for JavaScript means you have a much smaller set of objects, methods and properties to work with, and they all are focused towards dealing with HTML content. For example, JavaScript does not have the capability to control network connections or download files.

Why Is JavaScript So Hot?

Although based on programming, JavaScript is simple enough to be within easy reach of anyone who feels comfortable with HTML coding. It greatly expands the capabilities of typical HTML pages, without a great deal of hassle.

Look at the following snippet, for example:


<SCRIPT LANGUAGE="javascript">

document.writeln("This page last changed on "+document.lastModified());

</SCRIPT>

When the page loads, some basic information about itself also is included, such as the time and date the page was saved. Without any further communication with the server, JavaScript accesses the date and displays it for the user. You don't need to remember to update a line of HTML or include a link to a CGI script-when the JavaScript line appears, the process is automatic.

JavaScript also includes the capability to effectively manage multiple frames. Although a page cannot be redrawn, you can control the content in other frames by loading them with new URLs or managing form input.

Frames in Review
Frames enable multiple document windows simultaneously within one browser. Each frame can scroll, hyperlink, reload, and do all of the other things possible with a single browser window. Frames enable creation of useful document groups, such as combining menu and navigation bars with content. They are created with the <FRAMESET> tag, with each individual frame defined using FRAME SRC=URL NAME="name".
<HTML>
<FRAMESET ROWS="20%,80%">
    <FRAME SRC="MenuBar.htm" NAME="menu" noresize>
    <FRAMESET COLS="20%,80%">
        <FRAME SRC="NavBar.htm" NAME="nav" noresize>
        <FRAME SRC="Home.htm" NAME="body">
    </FRAMESET>
</FRAMESET>
</HTML>
Note the nested framesets for creating frames within frames. Be careful when using this feature. Although you can break down the browser screen into individual units, doing so can slow down displays and turn the screen into an unintelligible jigsaw puzzle-especially for a user screen with less than 800¥600 resolution.
Assigning names can make referencing frames easier, although referring to individual frames is also possible in JavaScript using the frames array.
When you create a frame, JavaScript adds an entry to its frames array. In the preceding example, JavaScript creates three entries:
document.frames[0].namne //"menu"
document.frames[1].name //"nav"
document.frames[2].name //"body"
As a general rule, JavaScript always begins numbering with 0, even in arrays. For more information on creating and working with frames, see Chapter 7 "Creating and Enhancing Web Pages with Frames."

One major JavaScript capability is revealed in its capability to handle forms and their elements. Using JavaScript, the information on a form can be validated and checked before it is sent to the server, saving valuable processing and communication time on the server. Client-side form processing also localizes the process, making it much harder for end users to send incompatible data that could cause damage to the server.

Additional characteristics now represent a part of form elements in the shape of events and event handlers. For INPUT TYPE= tags such as BUTTON and TEXT, the page author can check for mouse clicks, changed text, focus, and even change the content of form elements. In addition, submission of forms and other information is controlled by substituting custom actions for the standard submit button formats.

How to Use JavaScript Now

Most HTML editors that handle nonstandard HTML tags enable creation and editing of JavaScript sections to your pages. Several resources available for learning the syntax and idiosyncrasies of JavaScript appear at the end of this chapter.

Tip
One of the most useful sites is the JavaScript online documentation at http://home.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html.

For users to take advantage of your JavaScript-empowered pages, they need to use a compatible browser. This is a short list at present, but more browsers are expected to add this capability, following the example of the two leaders, Netscape and Microsoft.

Warning
The JavaScript API is not entirely stabilized yet. As Netscape continues its own development and collaboration with Sun, the implementation and workability of some features may change. You should always try your script on more than one browser and platform combination to ensure that your solutions function as planned.

The current browser choices include Netscape Navigator (2.0 and later) and Microsoft Internet Explorer (3.0 and later). Sun HotJava is also scheduled for JavaScript compatibility, although it hasn't been included in any of the beta implementations. ncSA Mosaic also includes support for Java and JavaScript on its wish list, although no date has been set for implementation.

Tip
Like many sites that provide a host of compatibilities, some of which are mutually exclusive, it shows good manners to offer your page in a generic version if crucial content is not usable with a non-JavaScript browser. You can also offer a link to sites where a compatible browser is available for downloading.

The <Script> Tag

As seen in the previous examples in this chapter, JavaScript requires its own special tag to mark its beginning and end. The basic form of the tag appears in the following code:


<SCRIPT [LANGUAGE="JavaScript"]>

...statments...

</SCRIPT>

A problem can develop when a noncompatible browser is used to view a page embedded with JavaScript statements. Note the following two figures (Figures 34.1 and 34.2). Both show the same HTML document, which includes JavaScript statements (see Listing 34.1); however, Figure 34.1 uses Netscape Navigator 3.0, and Figure 34.2 is viewed with ncSA Mosaic.


Listing 34.1. The contents of the HTML document used in Figures 34.1 and 34.2.

<HTML>

<HEAD>

<TITLE>JavaScript Test Page</TITLE>

<SCRIPT>

function checkJS () {

    alert("This browser is JavaScript-compatible.");

}

</SCRIPT>

</HEAD>

<BODY>

Checking for JavaScript compatibility.

<SCRIPT>

checkJS();

</SCRIPT>

</BODY>

</HTML>


Figure 34.1 : JavaScript-compatible Netscape Navigator 3.0 displays this HTML document and processes the JavaScript commands contained in it.

Figure 34.2 : The ncSA Mosaic browser is not yet JavaScript-compatible. The <SCRIPT> tags are ignored and the commands are processed as any other text.

A noncompatible browser ignores the <SCRIPT> tags and displays the JavaScript commands as any other text. For a document including any length of JavaScript, the result produces a screen full of commands and characters otherwise unintelligible to the user.

Hiding Scripts from Incompatible Browsers

Preventing an older or noncompatible browser from incorrectly processing your JavaScript code means correctly using HTML comment tags.

To hide your JavaScript, you must nest a set of HTML comment tags inside the <SCRIPT> tags. A JavaScript comment tag (two forward-slashes) must appear just before the closing comment tag to prevent it from being processed as another line of JavaScript and causing a syntax error (see Figure 34.3).

Figure 34.3 : ncSA Mosaic with the additional HTML comment tags displays the non-JavaScript content and passes over the part it can't interpret.


<SCRIPT LANGUAGE="JavaScript">

<!--  Note: An opening HTML comment tag.

...statements...

// --> Note: A JavaScript comment tag (two forward-slashes), 

followed by a closing HTML comment tag.

</SCRIPT>

With proper placement and usage, JavaScript can add vital functionality to your HTML pages without interfering with the capability of noncompatible browsers to interpret the document. Remember, however, that if your page depends on JavaScript for including crucial information or operability, it shows common courtesy to warn users and, if possible, supply a generic version of the document.

Placing Scripts on the Page

The <SCRIPT> tag can appear in either the HEAD or BODY section, although its placement will determine when and how the script gets used.

If placed in the HEAD portion of the document, the script gets interpreted before the page is completely downloaded (see Figure 34.4). This order works especially well for documents that depend on functions. The script is loaded and ready before the user has a chance to interact with any event that actually invokes the function (see Figure 34.5).

Figure 34.4 : The initial screen displayed by Listing 34.2. Note that the first line of JavaScript text and the alert box have appeared, but the text contained in the BODY portion of the document has not.

Figure 34.5 : The rest of the display generated by Listing 34.2 shows the HTML text in the body of the page and executes the function that was defined in the head.


Listing 34.2. Placing functions in the HEAD portion of the document ensures that they are interpreted before the rest of the document.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="javascript">

function printMessage(msgStr) {

    document.writeln("<HR>");

    document.writeln(msgStr);

    document.writeln("<HR>");

}

alert("Function is loaded and ready.");

</SCRIPT>

</HEAD>

<BODY>

Welcome to the body of an HTML page.

<SCRIPT LANGUAGE="javascript">

printMessage("I just called a function from the body.")

</SCRIPT>

</BODY>

</HTML>


Using JavaScript in Your Web Page

Many uses exist for JavaScript, and more continue to appear all the time as developers experiment with the possibilities opened with interactive HTML. This section shows a few areas and examples to get you started.

Note
A JavaScript ticker, which scrolls a message across the status bar, is absent from this list of applications. With Internet Explorer's <MARQUEE> tag and the availability of multifeatured Java ticker applets, the JavaScript ticker no longer provides an efficient use of browser cap-ability.

Computing Values Without CGI

One application for JavaScript that has gained a degree of popularity is a form, which returns values without being processed through a CGI script. One of the easiest ways to implement a form is by assigning a JavaScript function to a submit button rather than a URL. The function then examines the form's values, performs its various operations, and returns a value or values to the page (see Figure 34.6).

Figure 34.6 : This loan calculator accepts a variety of information about the term, payment schedule, and other items, and calculates the value next to the Compute button. The button calls a function that computes the affected value.

The syntax of the new button is <INPUT TYPE=BUTTON VALUE=Name onClick=JavaScriptFunction()>. When the button is clicked by the user, the function named after the onClick parameter (JavaScriptFunction()) is invoked. Other events are also supported by JavaScript, including changing a value or clicking on a field, using the same form of syntax. This enables you to recompute forms as the user enters or changes information (see Figure 34.7).

Figure 34.7 : One application that received many different treatments in JavaScript is the IRS Form 1040EZ After a user enters earnings and withholding information, pressing the button computes the tax bill.

As the user makes entries throughout the form, the fields that rely on those values are automatically updated and used, in turn, for the next computed value until the tax bill or refund is generated at the bottom.

Random Numbers

JavaScript includes a method of the Math object that generates random numbers, but in its current form it works only on UNIX machines. Another way of generating somewhat-random numbers exists using a user-defined function instead of the built-in method. It is referred to as a calculated random number, and can reveal its biases and true nonrandom nature if used repeatedly over a short period of time.

To ensure compatibility for a script across platforms, any script depending on random numbers shouldn't depend exclusively on the random method, but instead should rely on a generated number created by a function similar to the following example:


function UnixMachine() {

    if (navigator.appVersion.lastIndexOf('Unix') != -1)

        return true

    else

        return false

}



function randomNumber() {

    if UnixMachine()

        num = Math.random()

    else

        num = Math.abs(Math.sin(Date.getTime()));

    return num;

}

If the client machine has a UNIX base, randomNumber will use the built-in function. Otherwise, it generates a number between 0 and 1 by generating a sine based on the time value.

Javascript Time
Time in JavaScript is measured as the number of milliseconds elapsed since midnight on January 1, 1970, and is accessed by using the Date object or an instance of it. The Date object is dynamic, ever changing with the time. An instance of the object returns a static value, depending on the current value of Date or the date parameter passed to it.
The time is based on the client machine, not the server. One idiosyncrasy occurs in JavaScript's representation of time elements. The getMonth and setMonth methods both return a value from 0 (January) to 11 (December). When using these two methods, make sure to convert to the 1-12 system the rest of the world recognizes.
var birthday1 = new Date(96,1,11);
document.writeln(birthday1.getMonth()); //Returns a 1 (February)
var birthday2 = new Date("January 11, 1996 06:00:00");
document.writeln(birthday2.getMonth()); //Returns a 0 (January)

If you need a constant stream of random numbers, a sine-wave pattern will become evident. In this case, it becomes necessary to show some variation in the process by adding more variation into the calculation. You can do this by substituting a different computation (cos, log) at various intervals of time.

Status Bar Messages

With event handlers and the window.status property, JavaScript enables your browser to display custom messages in the status bar that respond to user actions. One of the most popular implementations is a descriptive line for hyperlinks (see Figure 34.8).

Figure 34.8 : A simple addition to the <A HREF> tag enables page authors to include useful statusbar messages to respond to actions such as placing the mouse over a hyperlink.


Best viewed with

<A HREF="http://www.microsoft.com" onMouseOver="window.status='The Microsoft Home 

	Page';return true">

Microsoft Internet Explorer</A>.

One problem with the status property is that it becomes the default message until either a browser-generated message overrides it or status is set to a different value. In the preceding ex-ample, The Microsoft Home Page remains in the status bar until another message preempts it.

To work around this problem requires the use of a timer. After passing the mouse over the hyperlink, the message displays, but only for a short time, after which the status bar is reset to a blank display. This setup requires two functions-one to write the message and set the timer, and one to erase the message:


timerLength = 1.5;

function writeStatus(str) {

    timeoutVal = timerLength * 1000;

    setTimeout("clearStatus()",timeoutVal);

    window.status = str;



}

function clearStatus() {

    window.status = "";

}

This method of generating status bar messages requires more lines of code, but it results in a cleaner operation for custom hyperlink messages. The message appears for the number of seconds assigned to timerLength, after which the clearStatus function is called to write a null string to the display. To invoke the new method, use the following example:


<a href="http://www.microsoft.com/" onMouseOver="writeStatus('Microsoft Home 

	Page'); return true;">

Microsoft</A>

Another possibility for this method of generating status-bar displays includes making a copy of the old value of window.status and restoring it when the timer expires.

Displaying the Current Date and Time

There are a growing number of ways to display the time on your Web page. Most of them involve server-side includes or objects dependent on helper applications. JavaScript offers live access to the system date, and used in conjunction with a timer feature, allows you to display the current time through a form field.

The first step is to build a simple form to hold the time field:


<FORM NAME="Clock">

<INPUT TYPE="Text" NAME="ClockFace">

</FORM>

Then, you'll need to fill the field with the date. JavaScript includes its own built-in date object, which can access the system date and store it in a variable. A simple way to do this is with a function:


<SCRIPT LANGUAGE="JavaScript">

function getTodayDate()

{

        var today = new Date();

        document.forms[0].todaydate.value = today;

}

</SCRIPT>

With these two in place, all that's needed is a way to call the function after the form is loaded:


<FORM NAME="Clock">

...

</FORM>

<SCRIPT>

getTodayDate();

</SCRIPT>

The date is now displayed on the user's screen (see Figure 34.9) in a static display.

Figure 34.9 : When the HTML page is loaded, the value for the clock is calculated and displayed using the JavaScript function. It is a static display-once it's posted, it won't change value with the passing of time.

Tip
If the user clicks on the field, he or she can obliterate the date by typing. This is one of the big drawbacks to a static JavaScript date and time display. A live clock, on the other hand, is constantly updated and prevents any permanent change to the field.

Displaying a live clock is a better use of JavaScript's capability, and it's not much harder to do. Instead of the getTodayDate function, substitute Listing 34.3.


Listing 34.3. A live clock function using JavaScript.

<SCRIPT LANGUAGE="JavaScript">

var timerID = null

var timerRunning = false

function stopClock(){

    if(timerRunning)

        clearTimeout(timerID)

    timerRunning = false

}

function startClock(){

    stopClock()

    displayTime()

}

function displayTime(){

    var Today = new Date();

    var mm = Today.getMonth()+1;

    var dd = Today.getDate();

    var hrs = Today.getHours();

    var min = Today.getMinutes();

    var theTime = "Date: " + mm + "/" + dd;

    theTime  += "  Time: " + ((hours > 12) ? hours - 12 : hours);

    theTime  += ((minutes < 10) ? ":0" : ":") + minutes;

    theTimeValue  += (hours >= 12) ? " P.M." : " A.M.";

    document.Clock.clockFace.value = timeValue;

    timerID = setTimeout("displayTime()",60000);

    timerRunning = true;

}

</SCRIPT>


To initialize the clock, substitute <BODY onLoad="startclock()"> for your usual <BODY> tag. This initializes the clock and starts it running when the page is loaded by the browser (see Figure 34.10). The time-out setting near the end of the script is used to update the clock every minute. Setting the value to 1000 and adding a variable for the seconds makes the clock seem even more "current."

Figure 34.10: The oncreen clock is now in a friendlier format and features constantly updated date and time.

Controlling Browser Behavior

One of the important and powerful capabilities of JavaScript is controlling various aspects of browser behavior and appearance. This feature comes in handy for implementing demonstrations and tours by adding the capability to spawn new browser windows with controllable levels of functionality.

The command syntax to create a new browser window is windowVar = window.open("URL", "windowName" [, "windowFeatures"]) where:

To include a feature, use the syntax windowFeature=yes or windowFeature=1. Conversely, to disable a feature use windowFeature=no or windowFeature=0.

The features include:

For example, use this code to open a plain window with hotlink-only navigation:


//Note: Setting one feature automatically sets all non-mentioned features to false.

window.open("URL", "windowName", "toolbar=no")

JavaScript Resources on the Internet

JavaScript gets used and talked about on the Internet frequently, making the Internet one of the first stops for information. You can find up-to-the-minute information on current implementations, bugs, workarounds, and new and creative uses.

Check out the JavaScript-enabled applications found through these resources for ideas and code snippets to include on your pages. If you see something you want to use, be sure to write the author of the page and ask permission first. It's not only good manners, it's the law; JavaScript and HTML documents are covered under copyright. However, in the usually friendly realm of the World Wide Web, most folks are more than happy to share the fruits of their labors.

Netscape

One of the first stops you make should be the home of the people who developed and implemented JavaScript. The Netscape site provides a place to look for new developments and documentation about JavaScript features. The complete JavaScript online documentation (see Figure 34.11) also appears here.

Figure 34.11: The Netscape site has an online manual on JavaScript, including objects, methods, and event handlers, It is also available for download in ZIP format.

You can access Netscape at http://home.netscape.com/. The JavaScript manual is located at http://home.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html.

Gamelan

This site provides one of the best places for examples of what other people are doing with JavaScript on the Web. Although Gamelan is geared more toward Java, it also includes one of the largest listings of JavaScript sites found anywhere on the Web. By perusing the examples here (see Figure 34.12), you can gain insight from others who have gone before you.

Figure 34.12: The Gamelan site offers one of the premier sites for JavaScript resources on the World Wide Web.

You can access Gamelan at http://www.gamelan.com/pages/Gamelan.javascript.html.

JavaScript Index

The JavaScript Index (see Figure 34.13) has a collection of real-life JavaScript examples and experiments, including a growing list of Web pages that illustrate some of JavaScript's features and capabilities. One of the pages included on the Index is a JavaScript Library, an expanding collection of source code from around the Web community.

Figure 34.13: The JavaScript Index has a solid source of examples and successful experiments from developers who are making JavaScript one of the fastest growing languages on the Internet.

You can access the JavaScript Index at http://www.c2.org/~andreww/javascript/.

The Unofficial JavaScript Resource Center

A well-designed site with a great deal of potential, the Unofficial JavaScript Resource (see Figure 34.14) remains shy on content in comparison with similar sites. It includes links to a variety of sites and several tutorials.

Figure 34.14: The Unofficial JavaScript Resource Center, a growing resource, offers examples and tutorials for getting the most out of scripting on your Web pages.

You can reach the site at http://www.ce.net/users/ryan/java/.

Summary

JavaScript adds new functionality and interactivity to HTML pages that in the past you could only attain through learning CGI scripting languages such as Perl. By switching the bulk of interactive behavior to the client side, it has also improved the perceived speed of World Wide Web sites as seen by the user.

Although it does have its nuances and idiosyncrasies, taking the time to learn JavaScript will pay off in supporting Web pages with dramatically improved features and functions that users will want to revisit again and again. More information on customizing and creating your own JavaScript-enabled pages is included in the next chapter, "Writing JavaScript Applications."