Previous Page TOC Next Page



- 32 -
Using JavaScript in Your Web Pages
by Rick Darnell


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 was typically submitted to the server for all processing, whether it was to check a zip code or put information in a database. Each time information was passed back and forth between client and server, the exchange slowed down the process because of inherently slow communication lines. JavaScript eliminates much of the client/server communication by shifting responses to user events to the client side; network transmission is not required, so the process is much faster.

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

What Is JavaScript?


JavaScript was developed by Netscape in conjunction with Sun's Java. It is also known as LiveScript—the name it had before the collaboration with Sun.



JavaScript Isn't Java

Java is an object-oriented programming language used to create stand-alone applications and a special type of mini-application for Web pages called an applet. Java is compiled into machine-independent bytecodes, which are in turn interpreted by the Java virtual machine on the host computer. Writing Java programs is easiest when you have some background in a programming language, such as C or C++.

JavaScript shares some of the same syntax and structure as Java, but it is much smaller and is simpler for people with HTML or CGI experience to use. It is interpreted along with the rest of the page at load time. JavaScript only resides 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 is quicker operation for the end user and less load on the server.

Although there are similarities between Java and JavaScript, the languages are different and intended for different uses. A simple form-handling routine that would require a significant amount of coding in Java is 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 one applet can communicate with another applet on the same page, communication between an applet and a page's HTML elements requires a substantial amount of code.


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

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

On the other hand, JavaScript has a much smaller set of objects, methods, and properties to work with, and they are all 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 is comfortable with HTML coding. It greatly expands the capabilities of typical HTML pages, without a lot of hassle.

Take the following example:




<SCRIPT LANGUAGE="javascript">



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



</SCRIPT>

When the page is loaded, some basic information about itself is also 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. There is no need to remember to update a line of HTML or include a link to a CGI script—after the JavaScript line is included, the process is automatic.

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



Frames

Frames make it possible to open multiple document windows simultaneously within one browser. Each frame can scroll, hyperlink, reload, and all of the other things possible with a single browser window. Frames enable creation of useful document groups, such as menu and navigation bars combined 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 frames. Although you can break down the browser screen into individual units, it can slow down displays and turn the screen into an unintelligible jigsaw puzzle, especially for a user screen with less than 800x600 resolution.

Assigning names can make referencing frames easier, although it is still possible in JavaScript using the frames array.

When a frame is created, 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.

One of the major powers of JavaScript 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's 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 are now 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 will enable the creation and editing of JavaScript sections in your pages. Several resources available for learning the syntax and idiosyncrasies of JavaScript are listed in the next-to-last section in this chapter.



Tip

One of the most useful sites is the JavaScript online documentation at

http://home.netscape.com/eng/mozilla/Gold/handbook/javascript/index.html

which is also available as a downloadable file.


In order for users to take advantage of your JavaScript-empowered pages, they'll need to use a compatible browser. The list is expanding, and it should include most of the popular applications by the beginning of 1997.



Caution

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 might change. It is always a good idea to try your script on more than one browser and platform combination to ensure your solutions will function as planned.


The current browser choices are 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 is also including support for Java and JavaScript support on its wish list, although a date has not been set for implementation.



Tip

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



Creating Scripts


Creating scripts is really quite simple, although proper syntax is a must to ensure success. Although a knowledge of object-oriented programming will definitely be an asset to anyone creating functions with JavaScript, it is not a necessity.

New Language, New Terminology


Objects, methods, properties, classes—it's an object-oriented world out there, and there's a whole new batch of terminology to go with it. Here's a quick primer on the basic terms that are used in conjunction with an object-oriented language such as JavaScript.



Tip

JavaScript is case-sensitive. For example, if you have a variable called rose, remember that rose is not a Rose is not a ROSE.



Object

Objects are at the heart of any object-oriented programming language, and JavaScript is no different. An object is a software representation typically used to represent a real-world object, along with a set of behaviors or circumstances. In JavaScript, built-in objects are also used to represent the structure, action, and state of an HTML page.

In object-oriented terminology, the actions are called methods and the states are called properties. Both of these terms are covered later in this section.

To build an object, you need to know something about it. Consider a squirrel, for example. A squirrel has several physical properties, including sex, age, size, color. It also has properties relating to its activity, such as running, jumping, eating peanuts, or tormenting a dog. Its methods relate to changes in behavior or state, such as run away, stop, and look, or twitch tail and chatter.

This is all well and good, but how do you represent this as an object in JavaScript? The basic object creation is a two-step process, beginning with defining a function that outlines the object, and then creating an instance of the object. Using some of the properties just listed, you can make a JavaScript squirrel. Listing 32.1 provides an object definition for a squirrel.

Listing 32.1. A JavaScript object definition for a squirrel.




function squirrel(color) {



    this.color = color;



    this.running = false;



    this.tormentingDog = false;



}



var groundSquirrel = new squirrel("brown")

The first part of the script with the function tag outlines the initial state for any given squirrel. It accepts one parameter, called color, which becomes a property, and adds two more properties called running and tormentingDog, which are both set to false by default.

By itself, the function does nothing—it has to be invoked and assigned to a variable. This is what happens in the next step, where a variable called groundSquirrel is created, whose color is brown. The object and its properties are represented like this:




groundSquirrel.color // "brown"



groundSquirrel.running // false



groundSquirrel.tormentingDog // false

Now, to implement the object as part of an HTML page (Figure 32.1), include the object definition between the <HEAD> tags. To see the object in motion, use Listing 32.2.

Listing 32.2. Use the JavaScript definition of a squirrel in an HTML document similar to this one.




<HTML>



<HEAD>



<TITLE>The Squirrel Page</TITLE>



<SCRIPT language="javascript">



<!--



function squirrel(color) {



    this.color = color;



    this.running = false;



    this.tormentingDog = false;



}



// -->



</SCRIPT>



</HEAD>



<BODY>



Making a squirrel...



<BR>



<SCRIPT LANGUAGE="javascript">



var brownSquirrel = new squirrel("brown");



document.writeln("brownSquirrel.color = "+brownSquirrel.color);



document.writeln("<BR>brownSquirrel.running = "+brownSquirrel.running);



document.writeln("<BR>brownSquirrel.tormentingDog = "+brownSquirrel.tormentingDog);



</SCRIPT>



</BODY>



</HTML>

Figure 32.1. The squirrel page creates a simple object and displays its properties.

Class

A class is the definition for a type of object. Although classes are in Java and not in JavaScript, it is helpful to understand what they are, because many discussions about either can refer to them.

Simply stated, a class is to an object as a blueprint is to a bicycle. A blueprint contains all the information about the bicycle, but you can't ride it. To ride a bicycle, you need to create an instance of it. In object-oriented terminology, this is called instantiation.

Classes can also have inheritance, which means they take on the behavior of other classes. A 10-speed bicycle and a tandem bicycle have bicycle characteristics, but different specific features and functions. They are considered subclasses of the bicycle class.

Although a JavaScript function definition is similar to a class, it can operate without instantiation.

Property

Properties are the individual states of an object, typically represented as variables. In the squirrel example, color, running and tormentingDog are all properties of squirrel. An object's properties can include any of the valid JavaScript variable types.



Which Type Is Which?

A variable's type is the kind of value it holds. There are several basic variable types offered by JavaScript, including string, Boolean, integer, and floating-point decimal.

JavaScript utilizes loose casting, which means a variable can assume different types at will. For example




squirrel.color = "pink"



...statements...



squirrel.color = 30



Both color values are valid. In Java, this would cause an error, because it incorporates tight casting. After a variable is assigned a type in Java, it can't be changed.

Loose casting can make your life easier when you are working with JavaScript. When you build strings, for example, you can add a string to an integer, and the result will be a string. For example




value = 3;



theResult = value + "is the number." //Results in "3 is the number."

The downside is that sometimes it's easy to forget what a variable thinks it is. It's a good idea to try and keep variables to their original type unless absolutely necessary.

Object properties are accessed using the object's name, followed by a period and the name of the property:




squirrel.color

Assigning a new value to the property will change it:




squirrel.color = "pink"

Function

A JavaScript function is a collection of statements that are invoked by using the name of the function and a list of arguments, if used. As a general rule, if you use a set of statements more than once as part of a page, it will probably be easier to include them as a function. Also, any activity used as part of an event handler should usually be defined as a function for ease of use.

Functions are normally included in the HEAD portion of the HTML document to ensure they are loaded and interpreted before the user has a chance to interact with them.

The syntax to define a function is




function functionName ([arg1] [,arg2] [,...]) {



    ...statements...



}

An example of a function that automatically generates a link to an anchor called top at the top of the current page could look like this:




function makeTopLink (topLinkText) {



    var topURL = "#top";



    document.writeln(topLinkText.link(topURL));



}

This function accepts a text string as its one argument and generates a hypertext link similar to using the HTML <A HREF> tags.




makeTopLink("Return to the top.");



makeTopLink("top");

Method

If properties are the current conditions of the object, methods are the knobs and levers that make it perform. Let's return to the squirrel example. Defining a squirrel was easy enough, but what about making it do something? First, the methods need to be defined as JavaScript functions.

The first method for our squirrel is to make him run and quit tormenting the dog.




function runAway() {



    this.running = true;



    this.tormentingDog = false;



    document.writeln("The squirrel is running away.");



}

The second method makes the squirrel stop moving and tease the dog.




function twitchTailChatter () {



    this.tormentingDog = true;



    this.running = false;



    document.writeln("The squirrel is being annoying.");



}

One more method would help us see what is happening to our squirrel as his state changes.




function showState() {



    document.writeln("<HR><BR>The state of the squirrel is:<UL>")



    document.writeln("<LI>Color: "+this.color+"</LI>");



    document.writeln("<LI>Running: "+this.running+"</LI>");



    document.writeln("<LI>Tormenting dog: "+this.tormentingDog+"</LI>");



    document.writeln("</UL><HR>");



}


Tip

HTML tags can be included in text written to the browser screen using JavaScript's write and writeln methods. These will be interpreted like any other HTML text, so formatting is possible for generated content.


Now that you have three methods defined, you need to make them a part of the object. This is a simple matter of including the method names as part of the object definition, as follows:




function squirrel(color) {



    this.color = color;



    this.running = false;



    this.tormentingDog = false;



    this.runAway = runAway;



    this.twitchTailChatter = twitchTailChatter;



    this.showState = showState;



}

Finally, the last step is including the whole package as part of an HTML document, such as Listing 32.3, and seeing if it works (see Figure 32.2).

Listing 32.3. Using the JavaScript definition of a squirrel and its behavior requires an HTML document similar to this one.




<HTML>



<HEAD>



<TITLE>The Squirrel Page</TITLE>



<SCRIPT language="javascript">



<!--



function runAway() {



    this.running = true;



    this.tormentingDog = false;



    document.writeln("The squirrel is running away.");



}



function twitchTailChatter () {



    this.tormentingDog = true;



    this.running = false;



    document.writeln("The squirrel is being annoying.");



}



function showState() {



    document.writeln("The state of "+this.name+" is:<UL>")



    document.writeln("<LI>"+this.name+".color: "+this.color+"</LI>");



    document.writeln("<LI>"+this.name+".running: "+this.running+"</LI>");



    document.writeln("<LI>"+this.name+".tormenting dog: "+this.tormentingDog+"</LI>");



    document.writeln("</UL><HR>");



}



function squirrel(color,squirrelName) {



    this.name = squirrelName;



    this.color = color;



    this.running = false;



    this.tormentingDog = false;



    this.runAway = runAway;



    this.twitchTailChatter = twitchTailChatter;



    this.showState = showState;



    document.writeln("A squirrel is born...");



}



// -->



</SCRIPT>



</HEAD>



<BODY>



<SCRIPT LANGUAGE="javascript">



var brownSquirrel = new squirrel("brown","brownSquirrel");



brownSquirrel.showState();



brownSquirrel.twitchTailChatter();



brownSquirrel.showState();



brownSquirrel.runAway();



brownSquirrel.showState();



</SCRIPT>



</BODY>



</HTML>

Figure 32.2. The browser screen displays the activity of the JavaScript object as each method is executed.

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 is




<SCRIPT [LANGUAGE="JavaScript"]>



...statments...



</SCRIPT>

A problem can develop when a page embedded with JavaScript statements is viewed by a noncompatible browser.

Note Figures 32.3 and 32.4. Both use the same HTML document (see Listing 32.4), which includes JavaScript statements, but Figure 32.3 is viewed with Internet Explorer 3.0, whereas Figure 32.4 is viewed with NCSA Mosaic.

Figure 32.3. JavaScript-compatible Internet Explorer 3.0 displays this HTML document and processes the JavaScript commands contained in it.

Figure 32.4. This browser, NCSA Mosaic, is not yet JavaScript-compatible. The <SCRIPT> tags are ignored and the commands are processed as any other text.

Listing 32.4. The contents of the HTML document used in Figures 32.3 and 32.4.




<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>

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

Hiding Scripts from Incompatible Browsers


To prevent an older or noncompatible browser from incorrectly processing your JavaScript code is a matter of correctly using HTML comment tags.

To hide your JavaScript, a set of HTML comment tags are nested inside the <SCRIPT> tags. A JavaScript comment tag (two forward slashes) is required just before the closing comment tag to prevent it from being processed as another line of JavaScript and causing a syntax error (see Figure 32.5).




<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>

Figure 32.5. NCSA Mosaic with the additional HTML comment tags will display the non-JavaScript content and pass over the part it can't interpret.

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

Placing Scripts on the Page


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

If you place it in the HEAD portion of the document, the script is interpreted before the page is completely downloaded (see Listing 32.5 and Figure 32.6). This is especially useful 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 32.7).

Listing 32.5. Placing functions in the HEAD portion of the document ensures 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>

Figure 32.6. The initial screen displayed by Listing 32.5. 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 32.7. The rest of the display generated by Listing 32.5 shows the HTML text in the body of the page and executes the function that was defined in the head.

Practical JavaScript For Web Pages


There are many uses for JavaScript, and more are being developed all the time as developers experiment with the possibilities opened with interactive HTML.

Here are a few areas and examples to get you started.



NOTE

Absent from this list of applications is a JavaScript ticker that scrolls a message across the status bar. With Internet Explorer's <MARQUEE> tag and the availability of multi-featured Java ticker applets, the JavaScript ticker is no longer an efficient use of browser capability.



Validating Forms


Using CGI scripts to validate forms wastes precious time and server time to conduct a process that can just as easily be conducted on the client. The time required for client/server communication is reduced, along with the lengthy development necessary for CGI scripts.

With its capability to interact with form elements, JavaScript is ideally suited to validate information directly on the HTML page. This localizes the process and takes advantage of the under-utilized client machine. Checking information on the client side also makes it much harder for users to send incompatible or damaging data to the server.

There are several methods to implement form validation, and most include adding a JavaScript function as the action of a Submit button. The HTML definition of the Submit button could look like this:




<INPUT TYPE="BUTTON" NAME="SUBMIT" VALUE="SUBMIT" onClick="checkInformation(this.form)">

checkInformation is a function that provides verification for the form to ensure that the information meets CGI script expectations. If not, it should return to the document without submitting to the server. It can also return focus to the offending items. If everything passes muster, then the function can also use the submit method:




function checkInformation(thisForm) {



    ...validation statements ...;



    if (validationPassed) {



        thisForm.submit(); }



    return;



}

Each form element becomes part of a form object with JavaScript. By using the name of the form as the name of the object, you can access each of the elements. If a name is not used, you can also use the forms array. The first form on the page is forms[0], the next is forms[1], and so on.

For an example, look at the following form definition:




<FORM NAME="validation">Enter your name and identification in the boxes.<BR>



Your name: <INPUT TYPE="text" NAME="userName" VALUE=""><BR>



User ID: <INPUT TYPE="text" NAME="userID" WIDTH="9" VALUE=""><BR>



<INPUT TYPE="button" NAME="button" VALUE="Submit" onClick="checkID(this.form)">



</FORM>

Each of the elements in this form are represented in JavaScript as




document.validation.userName



document.validation.userID



document.validation.button

The last element, a button, includes an event handler that calls the function checkID with the current form as the argument. Note that the name of the form is not needed in the call because the contents are passed as an argument in this.form. In the function (see Listing 32.6), the form is referred to as the name of the argument, formID.

Listing 32.6. A function that checks to make sure the lengths of two form elements are correct before submitting the form.




function checkID(formID) {



    val validUser = true;



    val validID = true;



    if (formID.userName.length != 10) {



        validUser = false;



        formID.userName.value = "Invalid Entry"; }



    if (formID.userID.length != 9) {



        validID = false;



        formID.userName.value = "Error"; }



    if (validUser && validID) {



        formID.submit(); }



    else {



        alert("Please try again."); }



}

Here's a section-by-section explanation to help you understand this function. First, two Boolean variables are initialized. These flags will indicate whether or not the validation has been passed when it comes time to check at the end of the function.

Next, the length of a form element named userName is checked. If the value doesn't equal (represented in JavaScript by !=) 10, then the valid flag is set to false, and the form element receives a new value, which is reflected immediately on the page.

The same process is repeated for the next form element, userID. At the end, if both flags are true (logical and is represented by &&), the form is submitted using the submit method. If either or both of the flags are false, then an alert screen appears.

Random Numbers


JavaScript includes a method of the Math object, which generates random numbers, but in its current form it only works on UNIX machines. There is another way of generating somewhat random numbers 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 and instead should rely on a generated number created by a function similar to this:




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 is UNIX-based, 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 will return 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. There is one idiosyncrasy 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, be sure to make the conversion 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 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 32.8).




More information is available from



<A HREF="http://www.microsoft.com" onMouseOver="window.status='The Microsoft Home Page';return true">



Microsoft Internet Explorer</A>.

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

One problem with the status property is that it becomes the default message until a browser generated message overrides it, or status is set to a different value. In the preceding example, "The Microsoft Home Page" will remain in the status bar until another message preempts it.

To work around this problem requires the use of a timer. After the mouse is passed over the hyperlink, the message is displayed, but only for a short time, after which it is reset to a blank display. This 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 results in a cleaner operation for custom hyperlink messages. The message is displayed 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.

Controlling Browser Behavior


One of the important and powerful capabilities of JavaScript is the capability to control various aspects of browser behavior and appearance. This is useful in implementing demonstrations and tours by adding the ability 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"])

windowVar is the name of a variable that holds the information about the new window.

URL is an address for the contents of the new window, and can be blank.

windowName is how the window will be referred to in frame and window references.

windowFeatures is a list of the individual features of the browser that should be included or excluded. If it is blank, all features are enabled. If only some features are included, any unmentioned features are disabled.

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 toolbar for the row of buttons at the top of the screen, status for the status bar at the bottom, scrollbars for the buttons and slides to control which part of the document is viewed, resizable for user control over the size of the browser, and width and height in pixels for the initial size.

Use this code to open a plain window with hotlink-only navigation:




//Note: Setting one feature automatically sets all nonmentioned features to false.



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

JavaScript Resources on the Internet


JavaScript is used and talked about on the Internet a lot, making the Internet one of the first stops for information. You can find up-to-the-minute information on current implementations, bugs, work-arounds, and new and creative uses.

Netscape


One of the first stops is at the home of the people who developed and implemented JavaScript. The Netscape site (http://home.netscape.com/) is the place to look for new developments and documentation about its features.

The complete JavaScript online documentation (see Figure 32.9) is also available at this site, along with a technical paper on cookies. The online manual is also contained in a ZIP file that is available for downloading.

The manual is located at




http://home.netscape.com/eng/mozilla/Gold/handbook/javascript/index.html

Figure 32.9. The Netscape site includes an online manual on JavaScript, including objects, methods, and event handlers.

Gamelan


This is one of the best places for examples of what other people are doing with JavaScript on the Web. Although Gamelan (see Figure 32.10) is more geared towards Java, it also includes one of the largest listings of JavaScript sites found anywhere. By perusing the examples at this site (http://www.gamelan.com/), you can gain a lot of insight from others who have gone before.

Figure 32.10. The Gamelan site is one of the premier sites for JavaScript resources on the World Wide Web.

JavaScript Index


The JavaScript Index (http://www.c2.org/~andreww/javascript/) is 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 (see Figure 32.11). One of the pages included on the Index is a JavaScript Library, which is an expanding collection of source code from around the Web community.

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

The Unofficial JavaScript Resource Center


A well-designed site with a lot of potential, the Unofficial JavaScript Resource Center (Figure 32.12) remains shy on content in comparison with similar sites. Although it includes links to a variety of sites, it also includes links to several tutorials.

The Resource Center is at




http://www.intercom.net/user/me/java/index.html

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

Voodoo JavaScript Tutorial


The Voodoo JavaScript Tutorial at




http://rummelplatz.uni-mannheim.de/~skoch/js/script.htm

is a set of lessons covering the various aspects of including JavaScript on your Web pages(see Figure 32.13). It is an evolving project with new lessons added periodically, so it's a good idea to check back periodically to see what's new.

You won't find much in the way of advanced material here, but what you will find is more than enough to get you beyond the beginner level.

Figure 32.13. The Voodoo JavaScript tutorial is a good place to pick up the basics of working with JavaScript, in addition to other HTML features such as frames.

JavaScript Newsgroup


This group (news://comp.lang.javascript) is frequented by many of the JavaScript gurus and is an excellent source of information, tips, and work-arounds. There is a high level of activity and the threads move quickly, so be sure to check every day if possible.

netscape.navigator


It never hurts to have a direct line monitored by the folks who developed JavaScript at Netscape, and netscape.navigator (news://secnews.netscape.com) is the closest thing there is. JavaScript topics are definitely in the minority in this group, but they're there if you look.

Note the different news server. The title implies it's secure, but it seems to be readily available for browsing and posting.

JavaScript Digest


Much like a chain letter, this is a running interactive discussion similar to the newsgroup. Once available in a digest format, it is also available in a standard form.

To subscribe, send a message to listproc@inquiry.com with the message set javascript mail ack.

If you have problems receiving the digest, send a message to listproc@inquiry.com with the message body "help." To unsubscribe to the list, send a message to listproc@inquiry.com with the message body unsubscribe JAVASCRIPT.

What's Next?


JavaScript adds new functionality and interactivity to HTML pages that in the past was only attainable 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 Web pages with dramatically improved features and functions that users will keep coming back to. To help you get started, a JavaScript reference is included as Appendix B.

With that in mind, the next section looks at how Internet Explorer fits into your life with real-world examples. This includes Chapter 33, "Developing Your Own Web Site" and Chapter 34, "Developing an Intranet," along with some of the rising stars in web technologies in Chapter 36, "New Technologies and Internet Explorer."

Previous Page Page Top TOC Next Page