by Rob McGregor
The Web is alive with interactivity these days, and one of the reasons for this is JavaScript. Although ActiveX components are the new kids on the block in bringing interactive content to the Web, JavaScript has already been around the block a few times. JavaScript has the capability to tie together Java applets and ActiveX components with highly interactive Web pages, providing an exciting Web browsing experience.
JavaScript is a scripting language that enables you to write scripts embedded in HTML pages, and it has features similar to VBScript (which was discussed in Chapter 8, "VBScript"). There are many parallels between the two scripting languages, but the underlying model is quite different. Before looking at just what JavaScript is and how it works, take a look at where it came from.
What is now known as JavaScript began life as a Netscape scripting language called LiveScript, originally designed for use with the Netscape LiveWire server software. The original idea was that network administrators could use LiveScript on both the server side and the client side. On the server side, administrators would control database connectivity, manage complex web sites, and automate many otherwise tedious administrative tasks. On the client side, Web page authors would be able to provide new and exciting interactive content in HTML code.
LiveScript was also designed to enable HTML authors to communicate with and control Java applets. Java is a programming language derived from C and C++, yet without many of the shortcomings inherent in these languages. Java provides a fully object-oriented programming model that has built-in security features that are well suited for writing applications and applets for the Internet. The idea was that the combination of Java applets and LiveScript would allow a much richer, much more immersive Web experience for the user.
In cooperation with Sun Microsystems, Netscape hammered the bugs out of LiveScript and folded in more Java-like syntax to their new scripting language. This resulted in the December, 1995, announcement that LiveScript would henceforth be known as JavaScript.
Note
Microsoft Internet Explorer 3.0 supports an implementation of JavaScript, known as JScript, through the Microsoft dynamic link library JSCRIPT.DLL.
It's important to realize that Java and JavaScript are two completely separate things. Although there is a similarity in syntax between the two, they are very different. Some important differences between JavaScript and Java are listed following:
Like all scripting languages, JavaScript has its own syntax, and the next section examines this syntax.
JavaScript borrows much of its syntax from Java, and Java borrows much of its syntax from C. So if you're familiar with Java, C, or C++, JavaScript should look pretty familiar, and it will probably be easier for you to use than VBScript.
A software object typically wraps some concept or functionality into an easy-to-use package. JavaScript, much like Java, expresses everything in terms of objects. An object typically contains properties, which define visual characteristics, and methods, which define functionality. The JavaScript language is composed of a rather simple hierarchy of two basic types of objects.
When you load an HTML page into a browser, several objects are created that correspond to the page and its contents. A page always has the following objects by default:
In addition to these default objects, your script can specify objects that are created automatically for use by the script when the page loads. The next section explores each of the basic JavaScript objects in greater detail.
Events occur in JavaScript in response to user actions in the browser window, and these events are available for various browser objects (described in the next section). The events defined for JavaScript objects are listed in Table 9.1.
As stated previously, JavaScript browser objects are those that are visible in a browser window. There are five main visible objects that you'll spend most of your time working with in JavaScript, and these are as follows:
There are many other objects in the hierarchy in addition to the five listed here. These other objects further refine the functionality of the main five, or provide ancillary services that enhance one of the main five objects.
Note
JavaScript uses an object-based hierarchy, not a true object-oriented hierarchy in the sense of Java or C++. JavaScript uses a simple containment hierarchy, so there can be no inheritance of properties or methods from parent to child as there is in Java and C++.
Take a closer look at each of the browser objects in the hierarchy to see what properties, methods, and events they provide.
The Window object is found at the top of the JavaScript hierarchy, and everything occurs within the context of the window. The window contains properties that apply to the entire window, and it holds the document that runs the JavaScript.
Note
There can be more than one window contained within the main window. Each child window in a frames document has a corresponding window object. Frames are discussed in the "Frame Object" section later in this chapter.
The window object contains two event handlers that can trigger some action in your scripts: onLoad and onUnload.
The onLoad and onUnload event handlers are used within either an HTML <BODY> tag or an HTML <FRAMESET> tag. For example, in a BODY tag these handlers might look like this:
<BODY onLoad="..." onUnload="...">
The "..." would be replaced by calls to some JavaScript functions (see the section "JavaScript Functions" later in this chapter for more information).
The window object contains several properties for use in your scripts, and Table 9.2 lists these properties.
A window object also contains these other objects as properties:
Although the defaultStatus property can be set at any time, it's typically done when a page loads. In this case, it's expressed as part of the window.onLoad statement in a <BODY> tag, as follows:
<BODY onLoad="window.defaultStatus='Set default text here...'">
The window object also exposes several methods for use in your scripts, and Table 9.3 lists these methods.
The frame object is a property of a window object, and it can be part of a frames array as well. Table 9.4 shows the properties of a frame.
Frames also provide the methods shown in Table 9.5.
A document object is a property of a window or frame object and embodies an HTML document. An HTML document is defined by the current URL and is composed of two sections:
Note
JavaScript functions are usually placed within the <HEAD> tag to ensure that they are loaded before the body, and that a user won't be able to inhibit JavaScript activity before a script is ready to handle user input.
A document object provides many properties for manipulating document data and appearance, and these are listed in Table 9.6.
These four JavaScript objects are also properties of the document object:
In addition to the properties listed in Table 9.6, the document object also provides the methods shown in Table 9.7.
The location object represents a complete URL, and the properties of a location object represent the different elements that make up a complete URL.
The location object provides the properties shown in Table 9.8 to provide information relevant to a location.
These properties are used as elements of a URL as follows:
protocol//hostname:port pathname search hash
A history object "remembers" where a user has been during the course of a browsing session. The history object has only one property: length. The length property reveals the number of entries in a history list. History lists are available for windows, frames, and documents, and Table 9.9 lists the methods available for this object.
A form is a very important construct for JavaScript, and form elements enable users to interact with a document through familiar user interface controls. Each form in a document is a distinct object composed of various other objects including
Table 9.10 shows the properties available for the form object.
A forms array has a single property, length, which reveals the number of forms in a document's forms array.
A form has a single method, submit, which sends data back to an HTTP server. The submit method returns data using one of two methods: get or post (specified by the method property).
A form also has a single event handler, onSubmit, which occurs when a user submits a form. This results in JavaScript code defined within the event handler being executed.
A text object is a single-line text input box in an HTML form that enables a user to enter text or numbers. Similarly, a textArea object is a multiple-line text input box in an HTML form that enables a user enter text or numbers. A password object is a single-line text input box in an HTML form that enables a user enter text or numbers but masks the values entered by displaying asterisks (*).
All three of these objects are closely related and have the same basic properties and methods. Table 9.11 shows the properties defined for these objects.
The defaultValue property is different for each of these objects, as follows:
Table 9.12 shows the methods defined for these objects.
There are three event handlers that correspond to the three methods listed in Table 9.12 and one additional method that fires when the value of a text, textArea, or password object changes. Table 9.13 shows the event handlers defined for these objects.
A hidden object is a form element used to pass value/name pairs when a form's data is submitted. As such, a hidden object must be defined within a <FORM> tag.
A hidden object has only two properties:
A button object is a pushbutton on an HTML form. A button has two properties:
A button has one method, click(), which simulates a mouse click on the button. A button also has a corresponding event handler, onClick, that fires when the button is clicked.
A radio object is an array of mutually exclusive radio buttons on an HTML form that enable a user to choose one item from a list. The radio object has a click() method and an onClick event handler, just like a button object. In addition, a radio object supports the properties listed in Table 9.14.
Note
All radio buttons in a group must be referenced by their index numbers within the radio button array.
A checkbox object is an HTML form element that can be toggled to checked or not checked (on or off). A checkbox object has a click() method and an onClick event handler, just like a button object. In addition, a checkbox object supports the properties listed in Table 9.15.
A select object is an HTML form element that can take two forms:
A select object has the properties listed in Table 9.16.
The options array contains an entry for each option in a select object, and the select object's options array itself has several properties. These properties are listed in Table 9.17.
In addition, select objects use the blur() and focus() methods described earlier, and the corresponding onBlur and onFocus event handlers, as well as the onChange event handler.
A submit object is a special button on an HTML form that causes a form's data to be submitted. A submit object supports the name and value properties discussed previously, as well as the click() method and the corresponding onClick event.
A link object is some text or image that acts as a hyperlink. When the link object is clicked, the link reference is loaded into its target window.
Note
A document stores link objects in an array that can be referenced by a link element. The length property reflects the number of links in a document.
A link object has several properties as listed in Table 9.18.
Link objects support two event handlers:
An anchor object is some text that can be the target of a link object. Anchor objects use the HTML <A> tag, and a document stores anchors in an array that can be referenced by an element index. A simple example of an anchor is as follows:
<A NAME="SomeAnchorName" SomeAnchorText </A>
In this example, the NAME attribute specifies a name called SomeAnchorName that can be jumped to from a link within the current document. The text SomeAnchorText specifies the text to display at the anchor. To jump to this anchor from somewhere within a document, you can use the following simple link object:
<A HREF=SomeAnchorName Go to the SomeAnchorName anchor.</A>
Built-in JavaScript objects don't have visible user interfaces, and they don't use event handlers. They are used within an HTML page to provide ancillary services for your scripts and are restricted to properties and methods. Three built-in objects are discussed in this chapter:
The date object represents a date and has several useful methods available for working with dates within a document.
The date object methods are listed in Table 9.19.
A string object represents a string of characters. The string object has only one property, length, which returns the number of characters in the string.
The string object provides a wide variety of methods for use in manipulating strings, and these are listed in Table 9.20.
The Math object has built-in properties and methods for mathematical constants and functions. This makes the use of complex mathematical equations easy in JavaScript! The following sections examine the properties and methods provided by this useful object.
The math object properties are actually just common, precalculated mathematical constants. These properties are very useful when performing complex calculations and are described in Table 9.21.
The Math object methods are useful mathematical functions, most with equivalents in the C runtime library. Table 9.22 lists these methods.
Note
The random() method is available on UNIX platforms only.
Now that you've looked at the objects, properties, methods, and events offered by JavaScript, take a look at some examples in HTML code.
A JavaScript applet is created using the HTML <SCRIPT> tag and by specifying the language to be JavaScript. Everything within the script block is part of the JavaScript, but standard HTML comments within a script block can be used to hide the script from browsers that don't support JavaScript. For example, the following HTML code uses a minimal script that displays the string "JavaScript rocks!" on the page box if the browser supports JavaScript:
<HTML> <HEAD> <TITLE>JavaScript Example 1</TITLE> </HEAD> <BODY> <H1>JavaScript Example 1</H1><HR> <SCRIPT LANGUAGE="JavaScript"> document.write("JavaScript rocks!!") </SCRIPT> </BODY> </HTML>
Figure 9.1 shows the result of the script in Internet Explorer 3.0.
Figure 9.1. A simple JavaScript in Internet Explorer 3.0.
This is fine for JavaScript-capable browsers, but browsers that don't understand JavaScript will simply display the JavaScript code in the page, as the CompuServe Mosaic browser does in Figure 9.2.
Figure 9.2. A script in a browser that doesn't understand JavaScript.
Because some users will undoubtedly use browsers that don't support JavaScript, you can prevent the script from appearing at all in these browsers by enclosing the entire script code in HTML comments. The revised code from the preceding example would give you this:
<HTML> <HEAD> <TITLE>JavaScript Example 1</TITLE> </HEAD> <BODY> <H1>JavaScript Example 1</H1><HR> <SCRIPT LANGUAGE="JavaScript"> <!-- Hide JavaScript from old browsers document.write("JavaScript rocks!!") // End code hiding --> </SCRIPT> </BODY> </HTML>
The real power of JavaScript begins to show when you add functions to the mix. As any modern programming language should, JavaScript supports the notion of functions that live in one area and can be called from elsewhere in the code. Where do JavaScript functions live in HTML? Typically in the <HEAD> section. This is because the function code will be loaded and interpreted before the page is displayed, and any JavaScript source that calls a function will have it available instantly.
A JavaScript function is defined (appropriately) by the keyword function, and it must fall within a <SCRIPT> block. The function is given a name, and this name can be called from a JavaScript code. Take a look at a function called displayMessage(), which takes a typeless parameter called msg and sends it to the JavaScript alert() method.
function displayMessage(msg) { alert(msg) }
This function could then be called by placing a form pushbutton on the page and calling the dislayMessage() function in response to the button's onClick event, like this:
<FORM> <INPUT TYPE="button" VALUE="Click Here..." onClick="displayMessage('Test message...')"> </FORM>
Note
The string Test message... is surrounded with single quotes. This is because they are nested within the double quotes used for the displayMessage() function call by the onClick event.
The complete source code for this function example is given in Listing 9.1.
Listing 9.1. Calling a function from within a JavaScript.
<HTML> <HEAD> <TITLE>JavaScript Example 2</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function displayMessage(msg) { alert(msg) } --> </SCRIPT> </HEAD> <BODY> <H1>JavaScript Example 2</H1><HR> This script calls a simple function...click the button! <FORM> <INPUT TYPE="button" VALUE="Click Here..." onClick="displayMessage('Test message...')"> </FORM> </BODY> </HTML>
In this example, the string "Test message..." is sent to the function displayMessage(), causing an alert box to appear. Now extend this into a more useful example by enabling a user to specify the text displayed in the alert box.
For this example, a text object named text1 is used to enable the user to input the text to display in the alert box. The showMessage() function is modified here to take a form object as a parameter, like this:
<SCRIPT LANGUAGE="JavaScript"> <!-- Updated showMessage() function takes a form as a parameter function showMessage(form) { if (form.text1.value.length > 0) alert("You entered the text: " + form.text1.value) else alert("You must enter some text!") } --> </SCRIPT>
Notice that if the length of the text isn't greater than zero, the script tells the user to enter some text; otherwise, the text is displayed using the form.text1.value property to get the string.
To enhance the page even more, the example uses a date object to extract information about when the page was last modified. This information is then written to the bottom of the page to provide automatic update information whenever the page changes, like this:
<H5> <SCRIPT LANGUAGE="JavaScript"> <!-- Hide script from old browsers update = new Date(document.lastModified) month = update.getMonth() + 1 date = update.getDate() year = update.getYear() document.writeln("<I>Last modified: " + month + "/" + date + "/" + year + "</I>") // End script hiding --> </SCRIPT> </H5>
The complete code listing for this example is given in Listing 9.2.
Listing 9.2. A page that gathers text data from a simple form and displays the document's last modified date.
<HTML> <HEAD> <TITLE>JavaScript Example 3</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- Updated showMessage() function takes a form as a parameter function showMessage(form) { if (form.text1.value.length > 0) alert("You entered the text: " + form.text1.value) else alert("You must enter some text!") } --> </SCRIPT> </HEAD> <BODY> <H1>JavaScript Example 3</H1> <HR> This script uses the data you enter in the text area and displays it in an alert box...click the button! <!-- Start a form for getting the text to use --> <FORM> <INPUT TYPE="button" VALUE="Click Here..." onClick="showMessage(this.form)"> <INPUT TYPE="text" SIZE=40 MAXLENGTH=256 NAME="text1"></p> </FORM> <!-- Show the last modified date in the document with this simple script --> <H5> <SCRIPT LANGUAGE="JavaScript"> <!-- Hide script from old browsers update = new Date(document.lastModified) month = update.getMonth() + 1 date = update.getDate() year = update.getYear() document.writeln("<I>Last modified: " + month + "/" + date + "/" + year + "</I>") // End script hiding --> </SCRIPT> </H5> </BODY> </HTML>
The results of this example can be seen in Figure 9.3, with the text box value displayed in an alert box, and the date the document was last modified displayed as part of the document.
Figure 9.3. EX3.HTM as it appears in Internet Explorer 3.0.
These few small examples should give you an idea of the power and ease of JavaScript. In Chapter 12, "Advanced Web Page Creation," you'll see some more useful and exciting examples for working with JavaScript and frames.
JavaScript provides a powerful way for Web page authors to add interactivity to Web pages with a well-structured scripting language. Programmers familiar with C, C++, or Java should have no trouble learning it. When combined with other tools and some imagination, JavaScript can provide the means to create a truly exciting Web browsing experience for the user.
The next chapter examines Microsoft's Web authoring tool FrontPage, a versatile and all-around excellent package for designing and maintaining Web sites.