In the last couple of days, you've learned about ways to add extra features and interactivity to your Web pages including image maps, forms, and CGI scripts. All these features, with the exception of client-side image maps, are available on most current browsers, so you can use those features freely without worrying too much about compatibility. However, these features also have a cost: almost all of them require interaction with the Web server, for scripts or for processing simple values, and, as such, they aren't the best solution for many kinds of presentations.
Today and in the next couple of days you'll learn about newer features on the Web and in browsers that add functionality to the browser itself and allow you to create new and interesting interactive presentations that do not rely so heavily on programs that run on the server side. The first of these newer features you'll learn about today is JavaScript.
JavaScript, formerly called LiveScript, is a programming language for adding functionality and features to HTML pages. JavaScript scripts are embedded in HTML files and run on the browser side. JavaScript is a Netscape innovation that has the support of many other commercial organizations, but, like many Netscape enhancements, it currently runs only on Netscape's browsers.
In this chapter, you'll learn about the basics of JavaScript by exploring the following topics:
According to the press release made jointly by Netscape Communications and Sun Microsystems, "JavaScript is an easy-to-use object scripting language designed for creating live online applications that link together objects and resources on both clients and servers. JavaScript is designed for use by HTML page authors and enterprise application developers to dynamically script the behavior of objects running on either a client or server."
Put into simple English, what this means is that by using JavaScript, you can add functionality to your Web pages, which in the past would have demanded access to complex CGI-based programs on a Web server. In many ways, JavaScript is a lot like Visual Basicthe user-friendly programming language developed by Microsoftin that even if you have little or no programming knowledge, you can use JavaScript to create complex Web-based applications.
What makes JavaScript different, however, is the unique way in which it integrates itself with the World Wide Web. Instead of being stored as a separate filelike a CGI scriptJavaScript code is included as part of a standard HTML document, just like any other HTML tags and elements. In addition, unlike CGI scripts, which run on a Web server, JavaScript scripts are run by the Web browser itself. Thus they are portable across any Web browser that includes JavaScript support, regardless of the computer type or operating system.
The answer to this question depends, to a certain extent, on exactly what capabilities are eventually included as part of the JavaScript language. It is likely, however, that scripts written using JavaScript will eventually be able to control all aspects of a Web page or Web form, and to communicate directly with plug-ins displayed on a Web page as well as with compiled Java applets.
But apart from such futuristic possibilities, what JavaScript enables you to do now is perform many simple (and not so simple) programming tasks at the Web browser (or client) end of the system, instead of relying on CGI scripts at the Web server end. In addition, JavaScript enables you to control with far greater efficiency the validation of information entered by readers on forms and other data-entry screens. And finally, when integrated with frames, JavaScript brings a wide variety of new document presentation options to the Web publishing domain.
Unlike Java, JavaScript is designed for nonprogrammers. As such, it is relatively easy to use and is far less pedantic about details such as the declaration of variable types. In addition, you do not need to compile JavaScript code before it can be usedsomething you need to do with most other languages, including Java.
As more and more people begin to flood the World Wide Web, many popular Web sites are rapidly being pushed to the limit of their current processing capabilities. As a result, Web operators are continually looking for ways to reduce the processing requirements for their systemsto ward off the need for expensive computer upgrades. This was one of the main reasons for the development of client-side image maps like those discussed in Chapter 17, "Image Maps."
With the introduction of JavaScript, some new performance options are now available to Web publishers. For example, say you have created a form that people use to enter their billing details for your online ordering system. When this form is submitted, the first thing your CGI script needs to do with it is validate the information provided and make sure that all the appropriate fields have been filled out correctly. You need to check that a name and address have been entered, that a billing method has been selected, that credit-card details have been completedand the list goes on.
But what happens if your CGI script discovers that some information is missing? In this case, you need to alert the reader that there are problems with the submission and then ask him to edit the details and resubmit the completed form. This involves sending the form back to the browser, having the reader resubmit it with the right information, revalidating it, and repeating that process until everything is current. This process is very resource intensive, both on the server side (as each CGI program run takes up CPU and memory time) and in the repeated network connections back and forth between the browser and the server.
By moving all the validation and checking procedures to the Web browserthrough the use of JavaScriptyou remove the need for any additional transactions because only one "valid" transaction will ever be transmitted back to the server. And, because the Web server does not need to perform any validations of its own, there is a considerable reduction in the amount of server hardware and processor resources required to submit a complex form.
With many Web service providers severely limiting the availability of CGI script support for security or performance reasons, JavaScript offers an method of regaining much of the missing CGI functionality. It moves tasks that would previously have been performed by a server-side CGI script onto the Web browser.
Most Web service providers usually furnish some form of basic CGI script, which can take a form submitted by a reader and perform basic processing operations such as saving it to disk or mailing it to the site's owner. When it comes to more complex forms, however, in the past the only alternatives were to find another service provider or set up your own Web server. But now, with JavaScript, this no longer needs to be the case.
By using a Web service provider's basic form-processing CGI scripts with JavaScript routines buried in the Web page itself, there are very few form-based activities that cannot be duplicated on even the most restrictive and security-conscious Web service provider's site. In addition, after the full integration of Java, JavaScript, and plug-ins has been achieved, you will be able to do things on a Web page that previously would never have been considered possible with even the most capable CGI script.
To accommodate the inclusion of JavaScript programs in a normal HTML document, Netscape has proposed the introduction of a new <SCRIPT> tag. By placing a <SCRIPT> tag in a document, you tell Netscape to treat any lines of text following the tag as scriptrather than as content for the Web page. This action then continues until a corresponding </SCRIPT> tag is encountered, at which point the Web browser reverts to its usual mode of operationtreating text as Web content.
When used in a document, every script tag must include a LANGUAGE attribute to declare the scripting language to be used. Currently, the two possible values for this attribute are LANGUAGE="LiveScript" and LANGUAGE="JavaScript". As a rule, however, you should always use the JavaScript optionLiveScript is included only for older scripts, and it's doubtful whether it will be supported in future Netscape releases.
When you include any JavaScript code in an HTML document, apart from using the <SCRIPT> tag, you should also follow a few other conventions:
Taking these three points into consideration, the basic structure for including JavaScript code inside an HTML document looks like this:
<HTML> <HEAD> <TITLE>Test script</TITLE> <SCRIPT LANGUAGE="JavaScript"> <! Use the start of a comment tag to hide the JavaScript code // Your JavaScript code goes here // close the comment tag on the line immediately before the </SCRIPT> tag > </SCRIPT> </HEAD> <BODY> Your Web document goes here </BODY> </HTML>
Besides the LANGUAGE attribute, the <SCRIPT> tag can also include a SRC attribute. Including the SRC attribute allows a JavaScript script stored in a separate file to be included as part of the current Web page. This is a handy option if you have several Web pages that all use the same JavaScript code and you don't want to copy and paste the scripts into each page's code.
When used like this, the <SCRIPT> tag takes the following form:
<SCRIPT LANGUAGE="JavaScript" SRC="http://www.myserver.com/script.js">
In this form, script can be any relative or absolute URL, and .js is the file extension for a JavaScript file.
At its heart, JavaScript uses an object-oriented approach to computer programming. This basically means that all the elements on a Web page are treated as objects that are grouped together to form a completed structure.
Using this structure, all the elements of a single Web page are said to be contained within a base object container called window. Inside the window object are a set of smaller containers (or objects) that hold information about the various elements of a Web browser page. These are some of the main objects:
location |
Inside the location object is information about the location of the current Web document, including its URL and separate components such as the protocol, domain name, path, and port. |
history |
The history object holds a record of all the sites a Web browser has visited during the current session, and it also gives you access to built-in functions that enable you to change the contents of the current window. |
document |
The document object contains the complete details of the current Web. This includes all the forms, form elements, links, and anchors. In addition, it provides many types of functions that enable you to programmatically alter the contents of items such as text boxes, radio buttons, and other form elements. |
form |
The form object contains information about any forms on the current Web page, including the action (the URL to submit the form to) and the method (get or post). The form object also contains information about the form elements contained in that form. |
You can find a complete list of the available objects in JavaScript as part of the Netscape JavaScript documentation at http://home.netscape.com/eng/mozilla/Gold/handbook/javascript/index.html.
Within each object container, there are two main types of resources you can access: properties and methods.
Properties are basically variables that hold a value associated with the object you're interested in. For example, within the document object, there is a property called title that contains the title of the current document as described by the <TITLE> tag.
In JavaScript, you obtain the value of this property by using the command document.title. The left side of the command tells JavaScript which object you want to work with, and the second partfollowing the dot (.)represents the name of the property itself.
Some examples of properties you can use include these:
document.bgcolor |
The color of the page background |
document.fgcolor |
The color of the page's text |
document.lastModified |
The date this page was last modified |
document.title |
The title of the current Web page |
form.action |
The URL of the CGI script to which the form will be submitted |
location.hostname |
The host name of the current Web page's URL |
See the JavaScript documentation at http://home.netscape.com/eng/mozilla/Gold/handbook/javascript/index.html for all the properties of each available object.
In addition to properties, most objects also have special functions associated with them called methods. Methods are a set of programming commands that are directly related to a particular object. For example, the document object has a method called write associated with it that enables you to write text directly onto a Web page. This method takes the following form:
document.write("Hello world");
As was the case for properties, you execute, or call, a method by first indicating the object it is associated with, followed by a dot and then the name of the the method itself. In addition, method names are followed by parentheses (). The parentheses surround any arguments to that methodfor example, if the method operates on numbers, the parentheses will contain the numbers. In the "Hello World" example, the write() method takes a string to write as an argument.
Note that even if a method takes no arguments, you'll still have to include the parentheses. So, for example, the toString() method, which belongs to the location object, is used to convert the current document's URL into a string suitable for use with other methods such as document.write(). There are no arguments to this method; you just call it with empty parentheses, like this: location.toString().
As with properties, each object has a set of methods you can use in your JavaScript scripts. The full list is at the same URL as the list of objects and properties mentioned earlier; here are a few choice methods:
document.write(string) |
Write HTML or text to the current page; string is the text to write. |
form.submit() |
Submit the form. |
window.alert(string) |
Pop up an alert box; string is the message to display in the alert. |
window.open(URL, name) |
Open a new browser window. URL is the URL of the page to open, and name is the windows name for frame or link target. |
By combining the document.write() and location.toString() methods and the document.title property mentioned previously into an HTML document like the following one, you can create a very simple JavaScript script such as the one shown here. The results are shown in Figure 23.1.
<HTML> <HEAD> <TITLE>Test JavaScript</TITLE> <SCRIPT LANGUAGE="JavaScript"> <! hide from old browsers document.write(document.title + "<BR>"); document.write(location.toString()); // done hiding > </SCRIPT> </HEAD> </HTML>
Figure 23.1. The results of your first JavaScript script.
Although implementing methods such as document.write() to create Web pages might have some uses, the real power behind JavaScript lies in its capability to respond to events.
Events are actions that occur on a Web page, normally when a reader interacts with the page in some way. For example, when a person enters a value into a text box on a form, or clicks a submit button, a series of events are triggered inside the Web browser, all of which can be intercepted by JavaScript programs, usually in the form of functions.
Functions are very similar to methods. The difference, however, is that whereas methods are associated with a specific object, functions are stand-alone routines that operate outside the bounds of an object. To define a function for the current Web page, you would write something like this:
<SCRIPT LANGUAGE="JavaScript"> function functionName( operands ) { The actions to be performed by your function go here } </SCRIPT>
In this code, functionName is any unique name you choose, and operands is a list of any values you want sent to the function. Following the function definition and inside the set of braces, { }, you include the list of instructions you want the function to perform. These could be a set of calculations, validation tests for a form, or just about anything else you can think of.
After you have your functions defined, the next thing you need to do is assign them to the various events you want trapped. You do this by assigning what are called event handlers to the various elements of a Web page or form. Currently, you can set the following event handlers:
Event Handler |
When It's Called |
onBlur |
Whenever a reader leaves a specified field |
onChange |
Whenever a reader changes the contents of a specified field |
onClick |
Whenever a reader clicks a specified button |
onFocus |
Whenever a reader enters a specified field |
onLoad |
Whenever a Web page is loaded or reloaded |
onMouseOver |
Whenever a reader places the mouse cursor over a specified field |
onSelect |
Whenever a reader selects the contents of a specified field |
onSubmit |
Whenever a reader submits a specified form |
onUnload |
Whenever the current Web page is changed |
To specify functions that should be associated with any of these events, all you need to do is include the appropriate event handler as an attribute of the field you want to control. For example, take a standard form with a couple of text fields and a submit button, as shown here:
<FORM METHOD="POST" SRC="../cgi-bin/form"> <INPUT TYPE="TEXT" NAME="username"> <INPUT TYPE="TEXT" NAME="emailAddress"> <INPUT TYPE="SUBMIT"> </FORM>
By adding onSubmit="return checkform( this )" to the <FORM> tag, the function called checkform() will be run before Netscape submits the form. In checkform(), you can do any checks you want and, if there are any problems, halt the form submission and ask the reader to fix them. The this parameter, inside the parentheses (()), is used to tell the checkform() function which form object is associated with the <FORM> tag. (You'll learn more about this in Chapter 24, "Working with JavaScript.")
In addition, you can do checking field by field, by including either onChange or onBlur event handlers in each <INPUT> tag. Because the onBlur handler is called each time a person leaves a field, it is ideal for input validation.
You can also include onClick events in buttons like the submit button which will be activated whenever the reader clicks the specified button. For example, the following code:
<INPUT TYPE="SUBMIT" onClick="processclick()">
would launch a function called processclick() whenever the submit button was clicked.
In addition to properties, JavaScript also enables you to assign or retrieve values from what are called variables. A variable is basically a user-defined container that can hold a number, some text, or an object. But unlike most high-level languages that force you to limit the contents of each variable to a specific type, in JavaScript variables are said to be loosely typed language. This means that you don't need to specify the type of information a variable contains when the variable is created. In fact, the same variable can be assigned to data of different types depending on your requirements.
To declare a variable for a JavaScript program, you would write this:
var variablename = value ;
In this form, variablename is any unique name you choose. The equals (=) sign following the variablename is called an assignment operator. It tells JavaScript to assign whatever is on the right side of the = signvalueas the contents of the variable. This value can be a text string, a number, a property, the results of a function, an array, a date, or even another variable. Here's an example:
var name = "Laura Lemay" ; var age = 28 ; var title = document.title ; var documenturl = location.toString() ; var myarray = new Array(10); var todaysdate = new Date(); var myname = anothername ;
After a variable has been defined, you can work with its contents, or alter them, by using what are called operators. Table 23.1 lists some of the more popular operators provided by JavaScript and includes an example that demonstrates the use of each. (As before, for a full list of all the supported operators, refer to the online JavaScript documentation.)
Operator |
Example |
Description |
+ |
a = b + c |
Add variables b and c, and assign the result to variable a. |
- |
a = b - c |
Subtract the value of variable c from variable b, and assign the result to variable a. |
* |
a = b * c |
Multiply variable b by variable c, and assign the result to variable a. |
/ |
a = b / c |
Divide variable b by variable c, and assign the result to variable a. |
% |
a = b % c |
Obtain the modulus of variable b when it is divided by variable c, and assign the result to variable a. (Note: modulus is a function that returns the remainder.) |
++ |
a = ++b |
Increment variable b by 1, and assign the result to variable a. |
|
a = b |
Decrement variable b by 1, and assign the result to variable a. |
There is also a special set of operators that combine the assignment function (=) and an operator into a single function. Such operators are called assignment operators. Table 23.2 lists the assignment operators provided by JavaScript.
AssignmentOperator |
Example |
Description |
+= |
a += b |
This is equivalent to the statement a = a + b. |
-= |
a -= b |
This is equivalent to the statement a = a - b. |
*= |
a *= b |
This is equivalent to the statement a = a * b. |
/= |
a /= b |
This is equivalent to the statement a = a / b. |
%= |
a %= b |
This is equivalent to the statement a = a % b. |
To tie together all the event handlers, methods, parameters, functions, variables, and operators, JavaScript includes a simple set of programming statements that are similar to those provided by Java and BASIC.
If you have any programming experience at all, spending a few minutes browsing through the list of supported statements discussed in Netscape Communication's online documentation will set you well on your way toward creating your first JavaScript programs. For those of you who don't have the experience, the following section includes a quick crash course on basic programming.
Regardless of what language you use, a program is simply a set of instructions that describe to a computer some action, or group of actions, you want it to perform. In the most basic case, this set of instructions starts at the beginning of a list of code and works through each instruction in the list one at a time, until it reaches the end:
<SCRIPT LANGUAGE="JavaScript"> // start of program - NOTE: lines that start with '//' are treated as comments document.write("step one") ; document.write("step two") ; // end of program </SCRIPT>
It is rare, however, that you'll ever want a program to proceed straight through a list of stepsespecially in JavaScriptbecause it would be easier to write the messages on the screen using HTML than to code them by using JavaScript. For this reason, most programming languages include a basic set of instructions that enable you to control the flow of the instructions.
The first such instruction is called the if statement. Basically, it enables you to perform tests inside program code to determine which parts of the program should be run under any given situation. For example, assume that you have a Web form that asks whether a person is male or female. In such cases, you might want to respond to the person using a gender-specific response, based on the indicated sex:
if ( form.theSex.value == "male" ) { document.write("Thank you for your response, Sir" ) ; } if ( form.theSex.value == "female") { document.write("Thank you for your response, Madam" ) ; }
If this piece of code were run and the property form.theSex.value had been assigned a value of "male", the first document.write() method would have been called. If it had been assigned a value of "female", the second statement would have been displayed. For the moment, don't worry about how the value form.theSex.value was assigned; you'll learn more about that issue in Chapter 24.
The block of code next to the if statement performs a comparison between the property form.theSex.value and the word "male". This comparison is controlled by what are called comparison operators. In this case, a test for equivalence was performed as signified by the == symbol. Table 23.3 lists the comparison operators currently recognized by JavaScript.
Operator |
Description |
Operator Notes |
== |
Equal |
a == b: tests to see if a equals b. |
!= |
Not equal |
a != b: tests to see if a does not equal b. |
< |
Less than |
a < b: tests to see if a is less than b. |
<= |
Less than or equal to |
a <= b: test to see if a is less than or equal to b. |
>= |
Greater than or equal to |
a >= b: tests to see if a is greater than or equal to b. |
> |
Greater than |
a > b: tests to see is a is greater that b. |
The preceding example could have also been written in a slightly different way, by using a different version of the if statement that incorporates an else statement:
if ( form.theSex.value == "male" ) { document.write("Thank you for your response, Sir" ) ; } else { document.write("Thank you for your response, Madam" ) ; }
In this example, because there is no need for a second if testbecause a person can be only male or femalethe else statement was used to tell the program to display the second message if the first test failed.
On occasion, you'll want a group of statements to run multiple times rather than just once. Two looping statements are supported by JavaScript to carry out this task. The first kind of statement, called a for loop, is ideal for situations in which you want a group of instructions to occur a specified number of times. The second kind, the while loop, is better suited to situations in which the number of loops required is to be determined by an outside source.
The basic structure of a for loop looks like this:
for (var count = 1; count <= 10; ++count ) { your statements go here }
In this example, a variable called count is declared and set to a value of 1. Then a test is made to see whether the value of count is less than or equal to 10. If it is, all the statements inside the braces, {}, following the for statement are executed once. The value of count is then incremented by 1 by the statement ++count, and the count <= 10 test is performed again. If the result is still true, all the instructions inside the braces are executed again. This process proceeds until the value of count is greater than 10, at which stage the for loop ends.
The basic structure of a while loop looks like this:
while ( condition ) { your statements go here }
Unlike the for loop, which has a built-in increment mechanism, the only test required for a while loop is a true result from the condition test following the while statement. This test could be an equivalence test, as in a == b, or any of the other tests mentioned previously in the if statement.
As long as this condition tests true, the statements inside the braces following the while loop will continue to run foreveror at least until you close your Web browser.
The list of statements, functions, and options included in this chapter represents only part of the potential offered by JavaScript. And in fact, JavaScript is still developing and changing with each release of Netscape's Navigator browser.
For this reason, I cannot overemphasize the importance of the online documentation provided by Netscape Communications (see Figure 23.2). All the latest JavaScript enhancements and features will be documented at http://home.netscape.com/eng/mozilla/Gold/handbook/javascript/index.html first. In addition, you'll want to check out http://home.netscape.com/eng/mozilla/Gold/handbook/javascript/index.html, which has more information about JavaScript in general, including examples of its use and more step-by-step tutorials.
Figure 23.2. The online JavaScript document at Netscape.
JavaScript offers HTML publishers the ability to include simple programs or scripts within a Web page without having to deal with the many difficulties usually associated with programming in high-level languages such as Java or C++.
In this chapter, you learned about the <SCRIPT> tag and how it is used to embed JavaScript programs into an HTML document. In addition, you also explored the basic structure of the JavaScript language and some of the statements and functions it offers.
With this basic knowledge behind you, in the next chapter you'll explore some real-world examples of JavaScript and learn more about the concepts involved in JavaScript programming.
Q: Don't you need a development environment to work with JavaScript?
A: Nope. As with HTML, all you need to write JavaScript scripts is a text editor. You may be confusing JavaScript with Java, a more comprehensive programming language that needs at least a compiler for its programs to run.
Q: Are Java and JavaScript compatible?
A: It depends on what you mean by "compatible." A lot of the syntax between Java and JavaScript is similar, but the connection between the two goes little further than that. JavaScript scripts will not compile using a Java compiler, nor can Java programs be included in an HTML file the way JavaScript scripts can. Java programs require a Java compiler and are then included as executable programs in Web pages, whereas JavaScript scripts are interpreted in code form as the HTML page is being downloaded.
Future versions of Netscape are rumored to contain objects and functions that will allow JavaScript programs and Java applets to interact, and that will allow Java applets to control aspects of the browser, which will bring JavaScript and Java much more closely together in terms of interoperability. But right now Java and JavaScript are similar but very different things with different purposes.
Q: In Java and C++, I used to define variables with statements such as int, char, and String. Why can't I do this in JavaScript?
A: Because you can't. As I mentioned previously, JavaScript is a very loosely typed language. This means that all variables can take any form and can even be changed on the fly. As a result, the type of value assigned to a variable automatically determines its type.