by Rick Darnell and William Robert Stanek
JavaScript is a scripting language that is included in HTML pages to increase their interactivity. This interactivity runs the gamut from alert boxes and status bar messages to complex menu systems and form validation.
It's based on Java, so if you're familiar with the way Java works, you'll be up and running with JavaScript in short order. However, because JavaScript is much smaller than Java and is geared specifically toward working with HTML pages, it is easy
enough for page authors with no programming experience to use.
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 LiveScriptthe first 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 applets, special "mini" applications for Web pages. 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 programming, such as with C or C++. JavaScript shares some of the same syntax and structure as Java but 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 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 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 requires 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 it 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 validating 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 writing code.
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 focus on dealing with HTML content. For example, JavaScript does not have the capability to control network
connections or download files.
Although based on a programming language, 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.
To see just how easy it is to create a script in JavaScript, open an existing Web page in the FrontPage Editor. Press Ctrl+End to jump to the bottom of the page. Click the Advanced toolbar's Insert Script button. Select JavaScript as your language and
then enter the following in the script input area:
document.writeln("This page last changed on "+document.lastModified);
Close the Script dialog box and save the page. The FrontPage Editor inserts the script into the page. An icon of a steaming red coffee cup marks the spot where the script is located.
NOTE
You can double-click the JavaScript icon at any time to edit your script. You can also easily move the script to a new location on the page. Click and hold the left mouse button on the icon and then drag the icon to a new location.
Now, load the page in your browser. When the page loads, some basic information about itself also got included, such as the time and date the page was saved. Without any further communication with the server, JavaScript accesses the page's modification
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 scriptonce 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.
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 pushbuttons and text boxes, the page author can check for mouse clicks, changed text, and 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.
FrontPage fully supports JavaScript. As you learned in Chapter 12, "Using Forms and the Form Page Wizard," you can use JavaScript with the Scripting Wizard to validate your forms before submitting them to a server. You can also use the
Scripting Wizard to automatically generate JavaScripts. To do this, you perform the same steps you learned in the section titled "Using the Scripting Wizard" from Chapter 29, "Creating Interactive Pages with VBScript and ActiveX." The
only thing you do differently is select JavaScript as your scripting language.
NOTE
Before you run off to use the Scripting Wizard to generate scripts, you should learn about JavaScript by reading this chapter. As you will find when using the Scripting Wizard, you really do need to understand basic JavaScript principles to create useful scripts. You will learn these principles in this chapter.
For users to take advantage of your JavaScript-empowered pages, they need to use a browser with a JavaScript interpreter. The current browser choices include Netscape Navigator (2.0 and later) and Microsoft Internet Explorer (3.0 and later). Although
this is a short list at present, more browsers are expected to add this capability following the example of the two leaders, Netscape and Microsoft.
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
As with 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.
A problem can develop when a user views a page embedded with JavaScript statements with a non-compatible browser. A non-compatible browser ignores the scripting 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. To prevent an older or non-compatible browser from incorrectly processing your JavaScript code, FrontPage hides the script from the
user's browser with HTML comment tags, which clears up the potential problem.
As JavaScript compatibility changes, here is a test you can use to see if a browser you want to use is JavaScript compatible:
function checkJS () { alert("This browser is JavaScript-compatible."); }
checkJS();
You can open the page in any browser you want to test. If the browser is JavaScript compatible, you see the alert box (see Figure 30.1). Otherwise, the alert box does not display.
Figure 30.1. Testing for JavaScript compatibility.
With proper placement and usage, JavaScript can add vital functionality to your HTML pages without interfering with the capability of non-compatible 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.
Creating scripts is really quite simple, although you must use proper syntax to ensure success. Although a knowledge of object-oriented programming proves useful to anyone creating functions with JavaScript, it is not a necessity.
Objects, methods, properties, classesan object-oriented world has taken off, and a whole new batch of terminology has cropped up to go with it. This section provides 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 your variable is called Bob, you can also have a BOB, bob, and Bob, and each one is unique unto itself.
Objects are at the heart of any object-oriented programming language, and JavaScript is no different. An object is a software model, typically used to represent a real-world object along with a set of behaviors or circumstances. In JavaScript, built-in
objects can also 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 as an 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 dogs. Its methods relate to changes in behavior or state, such as run away, stop and look, or twitch tail and chatter.
This example is all well and good, but how do you represent this idea 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 shown in the preceding example, you can make a JavaScript squirrel with Listing 30.1.
Listing 30.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, both set to false by default.
By itself, the function does nothingit has to be invoked and assigned to a variable. This is what happens in the next step, where a variable called groundSquirrel is created and given the color brown. The following
code shows how the object and its properties get represented:
groundSquirrel.color // "brown" groundSquirrel.running // false groundSquirrel.tormentingDog // false
Now, you can implement the object as part of an HTML page (see Figure 30.2). To see the object in motion, follow these steps:
function squirrel(color) { this.color = color; this.running = false; this.tormentingDog = false; }
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);
Figure 30.2. The squirrel page creates a simple object and displays its properties.
TIP
You can include HTML tags in text written to the browser screen using JavaScript's write and writeln methods. These methods are interpreted like any other HTML text, so you can include formatting for generated content.
A class represents the definition for a type of object. Although classes are in Java and not in JavaScript, it is helpful to understand classes because many discussions about either language may refer to them.
Simply stated, a class relates to an object as a blueprint relates 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 process is called instantiation.
Classes can also have inheritance, which means they take on the behavior of other classes. A ten-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 has a definition similar to a class, it can operate without instantiation.
Properties are the individual states of an object, typically represented as variables. In the squirrel example, color, running, and tormentingDog all represent
properties of squirrel. An object's properties can include any of the valid JavaScript variable types.
NOTE
A variable's type is the kind of value it holds. Several basic variable types are 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. Look at the following example:
squirrel.color = "pink" ...statements... squirrel.color = 30Both color values are valid. In Java, this causes an error because Java incorporates tight casting. Once a variable gets assigned a type in Java, it can't be changed.
Loose casting can make life easier when you're working with JavaScript. When building strings, for example, you can add a string to an integer, and the result is a string. Look at the following example:
value = 3; theResult = value + "is the number." //Results in "3 is the number."The downside is that sometimes you can easily 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 changes it.
squirrel.color = "pink"
A JavaScript function is a collection of statements that are invoked by using the name of the function and a list of arguments, if necessary. As a general rule, if you use a set of statements more than once as part of a page, it is probably easier to
include them as a function. Also, any activity used as part of an event handler should get defined as a function for ease of use.
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 looks 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:
makeTopLink("Return to the top."); makeTopLink("top");
If properties represent the current state of the object, methods serve as the knobs and levers that make it perform. Consider the squirrel example again. Defining a squirrel seemed easy enough, but what about making it do something? First, the methods
must be defined as JavaScript functions.
The first method for the squirrel makes 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 helps you see what happens to the 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>"); }
Now that you have three methods defined, you need to make them a part of the object. This step amounts to including the method names as part of the object definition.
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 and seeing if it works (see Figure 30.3). Here are the steps you can use to create this page:
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..."); }
var brownSquirrel = new squirrel("brown","brownSquirrel"); brownSquirrel.showState(); brownSquirrel.twitchTailChatter(); brownSquirrel.showState(); brownSquirrel.runAway(); brownSquirrel.showState();
Figure 30.3. The browser screen displays the activity of the JavaScript object as each method is executed.
One of the features that makes JavaScript so powerful is its capability to respond to events on the Web page. This feature includes using form elements, links, and buttons. Unlike the other JavaScript items, event handlers are not included within
script tagsthey are added as an additional parameter to the item they're monitoring.
To see how event handlers work, create a text field that responds when the user changes its value. Here are the steps:
function checkState(stateName) { if (stateName.toUpperCase() == "MONTANA") { window.alert("Glad you're in Montana"); } else { window.alert("Ride with me Mariah, in Montana."); } }
Steps 1-6 create a text field with a default value of MONTANA and add an event handler to call the function checkState when the value of the field changes. Users can simply press Enter to accept
the default or enter new information. Either event triggers the function call and displays one of two alert boxes (see Figure 30.4).
Figure 30.4. An alert box with the appropriate message is generated when JavaScript detects a change in the form field.
The checkState function looks at the value of the field. If it matches the default, it greets the user. Otherwise, it extends an invitation. This function is only invoked if the field changes from its current value. If the
user changes the field to Alaska, Nebraska, and then Wyoming, the function is called three times.
Another useful event handler is the onClick event, which can be used for pushbuttons, radio buttons, and pull-down lists. One popular usage is to call a validation routine before submitting the form contents back to the
server. This simplifies your CGI script on the server side by ensuring it only receives good data and speeds the operation on the user's side.
To try this validation, create a pushbutton. Name the button submit and give it a value of submit. However, do not select the Submit type. Instead, use the Normal button type.
Next, add an extended attribute for the pushbutton. Name this extended attribute onClick and use a value of validate(this). When the button is clicked, a function called validate is executed.
Note the difference in how the functions for the text control and the button control are called. One includes this.value and the other just this. When used within the confines of a form, this refers to the entire form, whereas this.value refers to the specific form element it's used in.
NOTE
JavaScript represents the various items on an HTML page using arrays. For example, a form is an array of the various elements within it. Consider the following form definition for two one-line text boxes and a drop-down list:
<FORM NAME="GUEST_INFO"> <INPUT TYPE="TEXT" NAME="Guest_Name"> <INPUT TYPE="TEXT" NAME="Guest_Email"> <SELECT NAME="Background" MULTIPLE> <OPTION VALUE="hardcore">Seasoned Web Surfer <OPTION VALUE="liar">Business Only <OPTION VALUE="newbie">Not For Sure How I Got Here </SELECT>Several arrays are created when a form is included in a document. The first is an array of forms in the document (document.forms[index]). The second is an array of the elements within the form (document.forms[index].elements[index]). The last is for list elements (document.forms[index].elements[index].options[index]).
This form example results in an array called document.Guest_Info, which is also referenced by its position in the document. If it's the first form on the document, it is also called document.forms[0] or document.forms["Guest_Info"].
Each of the form elements is an item within another array in the form. The second form element is called document.Guest_Info.Guest_Email, or another option, document.Guest_Info.elements[1].
The last array represented by this form is for the select elements. The naming of the specific element follows the preceding example, document.Guest_Info.Background, followed by one more object, options[index]. The second item in the select list is the preamble plus options[1] or options["liar"].
Although it seems like a terrible amount of typing, this ordering of your documents removes the ambiguity from identifying any item.
JavaScript offers a whole host of arithmetic operators and functions to help perform whatever computations you need within your scripts.
The first place to start are the basic operators used by JavaScript. Like other features of Java and JavaScript, the operators borrow its usage and syntax from the C and C+ programming languages.
Table 30.1 outlines the basic mathematical operators called binary operatorsthey need two operands in order to function.
Operator | Function |
* / % | Multiplication, division, modulus |
+ - | Addition, subtraction |
<< >> >>> | Bitwise shift left, shift right, shift right-zero fill |
A few operators on this list might not be familiar to you. Modulus is a simple division process that returns only the remainder of the operation.
6 % 2 //Returns 0 (2 goes into 6 three times with no remainder) 6 % 4 //Returns 2 (4 goes into 6 once with two leftover)
The last set, bitwise operators, shift the bits representing a number left or right. The numbers on both sides are converted to 32-bit integers, and then the bits on the left are moved the number of positions indicated by the number on the right. Bits
at the end are discarded.
NOTE
Do you remember bits and bytes from the early days of computers? They haven't gone away. JavaScript converts numbers in bitwise operations into 32-bit integers. For example, the number 156 is represented as 16 zeros plus 0000000010011100. Each bit represents a power of two, beginning on the far right with 2^0 and ending with 2^31. To decipher the number, add up the value of each position with a 1. In the 156 example, moving from right to left, you add 0+0+4+8+16+0+0+128.
You can combine all the binary operators with the assignment operator (=) to simplify other types of equations. For example, to increment a variable by 3 typically requires a statement such as
counter = counter + 3
This gets the job done but does require some extra typing. Combining the assignment and addition operator results in
counter += 3
The result is exactly the same. This processes the variable on the left and the value on the right using the operator and assigns the result to the variable.
Table 30.2 shows the next set of operators that you'll use most often, which are called unary because they work on a single operand.
Operator | Function |
++ -- | Increment, decrement |
! | Complement (boolean) |
- | Negation |
The increment and decrement operators are used to increase or decrease the value of a number by one. The placement of the operator determines when the calculation takes place. If it is placed after the operand, the operation happens after any other
calculation involving it is completed. If placed before, the value is updated, and then the rest of the calculation is finished.
count = 1 newValue = count++ //newValue = 1, count = 2 newValue = ++count //newValue = 3, count = 3
The complement is used to reverse the value of boolean. In the following example, if ready is false, then !ready is true. The text representation of the statement
is, "If not ready then...." This is an easier representation than if (ready == false).
if (!ready) { ... }
The last operator reverses the sign of a number from positive to negative and vice versa.
Relational operators are used to compare two values and return a true or false. The different options are listed in Table 30.3.
Operator | Function |
> < | Less than, greater than |
<= >= | Less than or equal, greater than or equal |
== != | Equals, doesn't equal |
?: | Conditional |
The first three sets are easy enough to understand. The last one is a special use of the relation and is often used to assign a value to a variable. The full syntax is
condition ? value if true : value if false
This is a shorthand for an if-then-else statement. The condition portion of the statement is any operation that results in a boolean true or false.
TIP
As an alternative to true and false, JavaScript also accepts 1 and 0, respectively. As a general rule, however, using a boolean expression results in greater clarity.
The following statement evaluates the value of age.
status = (age>=21) ? "Legal Drinking Age" : "Not Old Enough"
If the value is at least 21, then status is assigned the value Legal Drinking Age. If age is less than 21, then status is assigned Not Old Enough.
JavaScript includes a built-in object called Math. This object contains a whole host of useful functions and constants to save you time and typing. Here are a few of the items you'll find in Math.
First are the functions, which provide a handy method for easily computing several different types of equations:
In addition to the methods built into the Math object, JavaScript supplies a set of constant values. Because these are not methods and do not accept arguments, they do not use parentheses.
These constants represent values that are commonly used in math formulas. The most common of these is the value of pithe ratio of the diameter of the circle to the circumference. The value is approximately 3.1415927 and referred to as Math.PI.
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 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 multi-featured Java ticker applets, the JavaScript ticker no longer provides an efficient use of browser capability.
Many of the earlier examples showed that you could use JavaScript to write to the page. If you follow the example in this section and test it out, you should get a fair idea of the different ways you can use JavaScript to write to the page.
function printMessage(msgStr) { document.writeln("<HR>"); document.writeln(msgStr); document.writeln("<HR>"); } alert("Function is loaded and ready.");
printMessage("I just called a function from the body.");
Figure 30.5 shows how this page looks in a browser.
Figure 30.5. Writing to the page with JavaScript.
One of the applications for JavaScript that has gained a degree of popularity is a form that returns values without being processed through a CGI script.
One of the easiest ways to implement this form is by assigning a JavaScript function to the pushbutton, rather than an URL. The function then examines the form's values, performs its various operations, and returns a value or values to the page. The
loan calculator, shown in Figure 30.6, 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.
Figure 30.6. A loan calculator created with JavaScript.
The button has an extended attribute called onClick set to the value of a JavaScript function. When the button is clicked by the user, the function named after the onClick parameter is executed.
Other events are also supported by JavaScript, including changing a value or clicking a field, using the same syntax. This enables you to recompute forms as the user enters or changes information.
One of the applications that received many different treatments in JavaScript is the IRS Form 1040EZ (see Figure 30.7). After a user enters his various earnings and withholding information, the Submit button computes the tax bill.
Figure 30.7. A JavaScript-enhanced Form 1040EZ.
As the user moves through the form making entries, 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.
JavaScript includes a method of the Math object that generates random numbers, but in its current form, it only works on UNIX machines. Another way of generating somewhat-random numbers is to use 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 non-random 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
Listing 30.2.
Listing 30.2. Using random numbers.
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 uses the built-in function. Otherwise, it generates a number between 0 and 1 by generating a sine based on the time value.
NOTE
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 the values to the 1-12 system the rest of the world recognizes. Here is an example of using the getMonth() method:
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 use 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.
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 30.8).
Figure 30.8. A simple addition to the A HREF tag enables page authors to include useful status bar messages.
To add descriptions to your hyperlinks, open a Web page in the FrontPage Editor and perform the following steps:
window.status='your descriptive text here'; return true;
Here's an example:
window.status='The Virtual Press Home Page'; return true;
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 remains in the status bar until another message preempts it.
Working 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 functionsone to
write the message and set the timer and one to erase the message.
To use a timer in your page, enter the following script at the beginning of your page:
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 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 steps:
writeStatus('your message here'); return true;
Here's an example:
writeStatus('The Virtual Press Home Page'); return true;
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.
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 allows you to display the current time
through a form field when it's used in conjunction with a timer feature.
The first step is to build a form to hold the time field. You can do this as follows:
Next, you need to fill the field with the date. JavaScript includes its own built-in date object that can access the system date and store it in a variable. A simple way to do this is with a function.
To add a date function to your page, move the insertion point to the beginning of the page. Then, open the Script dialog box and select JavaScript as your scripting language. Enter the following script:
function getTodayDate() { var today = new Date(); document.forms[0].todaydate.value = today; }
With the form and the function in place, all that's needed is a way to call the function after the form is loaded. Move the insertion point to the end of the page on a new line after the form. Open the Script dialog box and select JavaScript as your
scripting language. Enter the following script:
getTodayDate();
Save the page and load it into your JavaScript-compatible browser. The date is now displayed on the page in a static display.
TIP
If the user clicks the field, 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. Replace the getTodayDate function with the script shown in Listing 30.3.
Listing 30.3. A live clock function using 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; }
To initialize the clock, you need to add an extended property to the page itself. Here are the necessary steps:
The extended attribute initializes the clock and starts it running when the page is loaded by the browser (see Figure 30.9). It does this by calling a function called startClock(). The startClock() function in turn calls the displayTime() function. If you examine the displayTime() function, you see a timeout setting near the end of the script. This setting
updates the clock every minute. Setting the value to 1000 and adding a variable for the seconds makes the clock seem even more current.
Figure 30.9. The on-screen clock is now in a friendlier format and features a constantly updated date and time.
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 the terms are defined as follows:
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 the following:
For example, insert this code to open a plain window with hotlink-only navigation:
//Setting one feature automatically sets all non-mentioned features to false. window.open("URL", "windowName", "toolbar=no")
JavaScript is used and discussed 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, work-arounds, 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.
One of the first stops you should make is 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 30.10) also appears here.
Figure 30.10. The Netscape site has an online manual on JavaScript.
You can access Netscape at http://home.netscape.com/. The JavaScript manual is accessible from http://www.netscape.com/comprod/products/navigator/version_3.0/index.html.
The Gamelan site provides one of the best places for examples of what other people are doing with JavaScript on the Web. Although Gamelan is more geared towards Java, it also includes one of the largest listings of JavaScript sites found anywhere on
the Web. By perusing the examples here (see Figure 30.11), you can gain insight from others who have gone before you.
Figure 30.11. 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.
The JavaScript Index (see Figure 30.12) 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 30.12. The JavaScript Index has a solid source of examples and successful experiments from developers.
You can access the JavaScript Index at http://www.c2.org/~andreww/javascript/.
A well-designed site with a great deal of potential, the Unofficial JavaScript Resource (see Figure 30.13) remains shy on content in comparison with similar sites. This site includes links to a variety of sites, as well as links to several tutorials.
You can reach the site at http://www.ce.net/users/ryan/java/.
Figure 30.13. The Unofficial JavaScript Resource Center, a growing resource, offers examples and tutorials.
The JavaScript group is frequented by many of the JavaScript gurus and provides an excellent source of information, tips, and work-arounds. A high level of activity occurs and the threads move quickly, so make sure to check everyday if possible.
You can reach the JavaScript newsgroup at news://comp.lang.javascript.
It never hurts to have a direct line monitored by the folks who developed JavaScript at Netscape, and netscape.navigator remains the closest thing to that line. JavaScript topics are definitely in the minority in this
group, but you can find them 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. To get there, use news://secnews.netscape.com.
Much like a chain letter, the JavaScript Digest site serves as a running interactive discussion similar to the newsgroup. Once available in a digest format, it also comes 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.
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 pays off in supporting Web pages with dramatically improved features and functions that users will want
to revisit again and again.