Notice: This material is excerpted from Special Edition Using Java, ISBN: 0-7897-0604-0. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.
by Jerry Ablan
Becoming proficient in a new programming language can take quite a while. People who have been programming for years occasionally learn new tricks. Besides learning the language's syntax and grammar, shifting his or her thoughts to the land of the new language takes a programmer some time.
At this point in the book, you probably have dozens of ideas for cool applets to implement on your Web site. But writing a complete applet takes time and a decent understanding of the Java language. Wouldn't it be nice to simply add the required functionality to your Web page?
Suppose that you want to create an applet that scrolls information in the help bar of the browser. Coding and testing a complete applet could take several days. Adding a little snippet of code to your Web page to perform that single function would be great. Browser script languages allow you to perform these simple feats without coding entire Java applets.
This chapter will cover the following topics:
Smart browsers JavaScript VBScript Using scripts in your Web pages
Web browsers are fairly unintelligent; they simply request, retrieve, and display the content of documents from various servers. If you want to add something unique to your Web site, you have to create a program on the server that modifies the document before it is sent to the browser. Instead of doing any modifications to the document at the browser, the changes are made before the document is sent. This is referred to as a server-side modification because the changes are made at the server's side of the connection. These modifications are performed by scripts and processes called server-side programs.
But creating server-side programs can be a headache. And for many people, creating such programs is not even an option; writing these programs involve UNIX programming skills that many people don't have. In addition, if you have a home page with an Internet Service Provider, you may not have the capability to create server-side scripts and programs. Many ISPs offer these services only to their corporate clients.
Although browsers are large and have many functions, they are essentially unintelligent; they run, retrieve, and browse Web pages, and then they end. Browsers can interact with a variety of servers: HTTP, FTP, and Gopher, to name a few. But the basic browser is a multimedia display tool-nothing more.
To make the browser smarter, you have to add some client-side capabilities that allow a retrieved document to modify itself or the retrieving browser. This capability moves the power of server-side programs to the client, in essence empowering the browser and making it smarter.
One client-side capability that is available is a script language. Scripts allow a Web browser to intelligently deal with situations that otherwise would require a program on the Web server. In addition, the user's perception is that the situation is handled much faster, because the browser does not need to send the request to the server and display the response.
In December 1995, Netscape Communications Corporation and Sun Microsystems announced a new scripting language called JavaScript. JavaScript is an open, cross-platform scripting language that complements the features of Java. JavaScript is easy to learn, even by users who have little or no programming background. JavaScript was first available in the beta versions of Netscape Navigator 2.0.
According to the original press release for JavaScript, 28 companies endorse JavaScript as an open-standard, object scripting language and intend to provide support for it in their future products. These companies include America Online, Apple Computer, Borland International, Novell, and Oracle.
JavaScript is similar to Java in syntax but is by no means "Java Lite" or a slimmed-down version of Java. JavaScript is a complementary language that provides some of the features of Java without requiring the user to learn object-oriented programming. JavaScript can recognize and respond to various events that are generated by the browser software, including mouse clicks and movements, page loading, and form input.
JavaScript scripts are embedded in Web documents and are executed by the browser at various points of the document's retrieval. This distinction between Java and JavaScript is important. Java applets must be compiled and downloaded by the browser before they are executed; JavaScript scripts are simply downloaded and interpreted.
An excellent use of JavaScript is to perform error checking in online forms. If you have forms that rely on a server-side program to perform error checking, you can perform the check at the client with JavaScript. This allows, for instance, an instantaneous response to a user entering invalid information into a form. An interesting use of form checking calculations is the 1040-EZ form Web page. Figure 18.1 is what this page looks like.
Fig. 18.1 The 1040-EZ Web page uses JavaScript to check the form values entered by the user.
Another use is to perform calculations at the client instead of the server. Perhaps you have a Web site that amortizes home loans. The user inputs his or her data and then submits the form to the server. The server spawns a CGI program to calculate the results, which are sent back to the client for display. With JavaScript, the entire calculation can be performed at the client, by the client, thereby reducing network traffic and the time needed for transmission of data. Books Galore is a Web site designed to show off the features of JavaScript. Figure 18.2 shows one of its pages.
19FIG02 This site uses JavaScript to check the total quantities and which books are selected. It automatically calculates the tax and total for a book order as well.
Like a programming language, JavaScript has variables. But conventional programming languages (like C, C++, and Java) require the programmer to declare the type of data that is to be stored in the variable. This is called static typing of variables. JavaScript has the opposite of this: loose typing. That is to say that variable types are never declared, they are implied. Variables become a certain type depending on the data that is placed inside of it. They may also change type on the fly. If you assign a string value to a variable, you may later change it to a boolean. Whichever value is currently in the variable defines the type.
For example, if you have a variable called booFar, and you initialize it with a string value, the variable then becomes a string.
var booFar = "Hi there!";
Later in your script, you can place another value type in it like this:
var booFar = 3421.34
The variable changes to hold the information automatically.
In Java, you must declare the variable as a string before attempting to place any string data into it.
String booFar = "Hi there!";
Once a type has been chosen in a static typed language, any value other than the original type must be converted before assignment. With JavaScript, this conversion is done for you.
JavaScript is not capable of defining classes. Although you can create instances of internal or Java classes, you cannot create classes with JavaScript. You also cannot inherit new classes from internal or Java classes.
JavaScript supports four basic types of variables:
doesThisWork = True; isThisBroken = False;
aFloat = 123.45; anInt = 3492;
userName = "munster"; emailAddress = "munster@mcs.net";
today = new Date(); aDate = new Date( 1971, 4, 12 );
In addition, JavaScript supports arrays of any data type.
JavaScript is based on the idea that an object is an entity that has defined properties. These properties can be variables or other objects. All properties can be manipulated with JavaScript and are considered to be variables. An object also can include functions. As in Java, these functions are called methods.
Manipulating the property of an object in JavaScript is similar to Java and other programming languages. They use the dot-notation to drill-down into the object.
For example, one of the internal objects available to JavaScript is called navigator. This object holds information about the browser the user is running. One of the navigator properties is appName. This string property contains the name of the browser. To get the value of this property, you use dot-notation by placing a period, or dot, in between the object and the property like this:
navigator.appName
Any property of any object can be interrogated in this fashion. In addition, a property may be another object, so you can drill-down even further to reach the property desired. The next section will introduce you to more of JavaScript's internal objects and have some examples.
This model is similar to C and C++, as well as to higher-level languages such as Visual Basic, PowerBuilder's PowerScript, and Smalltalk.
JavaScript comes with a rich set of built-in objects. These objects give the programmer access to form controls and to browser, server, and document information. All these objects have their own properties and associated events. The properties of these objects can be manipulated and interrogated. The events generated by these objects can trigger the execution of other scripts as well.
Four very important objects are available with every retrieved document:
Figure 18.3 shows the window object hierarchy.
Fig. 18.3 The hierarchy of the window object
To familiarize yourself with these objects, create the sample HTML page shown in listing 18.1.
Listing 18.1 Sample HTML Document <html> <head> <title>Sample HTML Document</title> </head> <body text="#000000" bgcolor="#FFFFFF" link="#0000EE" vlink="#551A8B" alink="#FF0000"> <p> <script language="JavaScript"> <!-- Non-Aware Browsers will ignore this // // Function: handleClick // // Moves values into the display field. // function handleClick( theButton, theForm ) { if ( theButton.name == "Button_Me" ) theForm.total.value = "You pressed me!"; else { if ( theButton.name == "Button_Him" ) theForm.total.value = "I said to press the other button!!"; else if ( theButton.name == "Clear" ) theForm.total.value = ""; } } // End of script --> </script> This is a sample HTML document. </p> <p> <form NAME="myForm"><font SIZE=+2>Stuff </font> <input name="Total" size=50></input> <p> <input TYPE="button" NAME="Button_Me" VALUE="Press Me" onClick="handleClick( this, this.form )"></input> <p> <input TYPE="button" NAME="Button_Him" VALUE="Press The Other Button" onClick="handleClick( this, this.form )"></input> <p> <input TYPE="button" NAME="Clear" VALUE="Clear Stuff" onClick="handleClick( this, this.form )"></input> <p> </form> <p> <script language="JavaScript"> <!-- Non-Aware Browsers will ignore this document.writeln( "Loaded Document: " + location.href + "<br>" ); document.writeln( "Document Title: " + document.title + "<br>" ); document.writeln( "<P>" ); document.writeln( "This document contains " + document.myForm.elements.length + " form elements. <p>" ); for ( var i = 0; i < document.myForm.elements.length; i++ ) { document.writeln( "Element #" + ( i + 1 ) + " is named " + document.myForm.elements[ i ].name ); document.writeln( " and has a value of \"" + document.myForm.elements[ i ].value + "\"<br>" ); } // End of script --> </script> </body> </html>
Here are some of the object properties used in the above example:
location.href = "http://www.netgeeks.com/junk/sample.html" document.title = "Sample HTML Document" document.myForm.Button_Me.name = "Button_Me"
The preceding items are only examples; the values depend on the location and content of the target document.
Figure 18.4 shows the result of the HTML document from listing 18.1.
Fig. 18.4 The results of loading the sample document.
Even though JavaScript is relatively new, many Internet resources are already devoted to JavaScript. Following are a few of the better sites:
Another scripting language soon will be available from Microsoft. This language is called Visual Basic Script (VB Script for short). VBScript, which is a slimmed-down version of Visual Basic for Applications (VBA), initially will be available for Microsoft's Internet Explorer.
VB Script is similar to JavaScript in that it lives inside HTML documents. The resemblance, however, end there. While JavaScript is closer to Java (or C and C++) in syntax, VB Script is actual Visual Basic code. VB Script allows you to embed Visual Basic code into your documents. When a VB Script enabled Web browser reaches the <SCRIPT> tag, the code is compiled and executed. Listing 18.2 shows a sample VB Script script.
Listing 18.2 Sample VB Script script <SCRIPT> Sub Button_Me_click Total.Text = "He clicked me!" End Sub </SCRIPT>
VB Script will also be capable of OLE automation. This will allow you to get and set properties of OLE and Java objects that are embedded within an HTML document.
Not much more information was available about VBScript at the time when this chapter was written. Developments occur quickly, however, so check out the following Microsoft Web site from time to time: http://www.microsoft.com/intdev
The <SCRIPT> Tag
How do script languages find their way into an HTML document? The languages use a new HTML extension: the <SCRIPT> tag.
The <SCRIPT> tag can be placed anywhere in the <BODY> or <HEAD> section of an HTML document. If the script is placed in the <HEAD> portion, however, it is interpreted before the body of the document is fully received. Because of this, you should place functions and initialization code into the <HEAD> portion. That code will be available throughout the life of the document.
You can place <SCRIPT> tags throughout your HTML document. A common practice is to place a <SCRIPT> tag within the <HEAD> portion of a document to hold functions. These functions then are available to the entire document. You can place other <SCRIPT> tags in the <BODY> section of your document to call these functions or to provide information as shown in listing 18.1.
Remember to follow each <SCRIPT> tag with </SCRIPT>. This tag signifies the end of an HTML script block.
The <SCRIPT> tag has one optional parameter. This parameter is the LANGUAGE parameter. It is used to specify the language in which the script is written.
This is useful to the browser to ignore scripts in languages that it does not support and allows for other languages to be developed. Currently, the only language that the Netscape Navigator software supports is JavaScript.
For technical support for our books and software contact support@mcp.com
Copyright ©1996, Que Corporation