home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


JavaScript: The Definitive Guide

Previous Chapter 1
Introduction to JavaScript
Next
 

1.3 What JavaScript Can Do

JavaScript is a relatively general-purpose programming language, and, as such, you can write programs in it to perform arbitrary computations. You can write simple scripts, for example, that compute Fibonacci numbers, or search for primes. In the context of the Web and web browsers, however, these aren't particularly interesting applications of the language. As mentioned earlier, the real power of JavaScript lies in the browser and document-based objects that the language supports. To give you an idea of JavaScript's potential, the following subsections list and explain the important capabilities of JavaScript and of the objects it supports.

Control Document Appearance and Content

The JavaScript Document object, through its write() method that we have already seen, allows you to write arbitrary HTML into a document as the document is being parsed by the browser. For example, this allows you to always include today's date in a document, or to display different text on different platforms, or even perhaps extra text to appear only on those browsers that support JavaScript.

You can also use the Document object to generate documents entirely from scratch. Furthermore, properties of the Document object allow you to specify colors for the document background, the text, and for the hypertext links within it. What this amounts to is the ability to generate dynamic and conditional HTML documents, a technique that works particularly well in multiframe documents. Indeed, in some cases, dynamic generation of frame contents allows a JavaScript program to entirely replace the use of a traditional CGI script.

Control the Browser

Several JavaScript objects allow control over the behavior of the browser. The Window object supports methods to pop up dialog boxes to display simple messages to the user and to get simple input from the user. This object also defines a method to create and open (and close) entirely new browser windows, which can have any specified size and can have any combination of user controls. This allows you, for example, to open up multiple windows to give the user multiple views of your web site. New browser windows are also useful for temporary display of generated HTML, and, when created without the menu bar and other user controls, can serve as dialog boxes for more complex messages or user input.

JavaScript does not define methods that allow you to directly create and manipulate frames within a browser window. However, the ability to dynamically generate HTML allows you to programmatically write the HTML tags that will create any desired frame layout.

JavaScript also allows control over which web pages are displayed in the browser. The Location object allows you to download and display the contents of any URL in any window or frame of the browser. The History object allows you to move forward and back within the user's browsing history, simulating the action of the browser's Forward and Back buttons.

Finally, yet another method of the Window object allows JavaScript to display arbitrary messages to the user in the status line of any browser window.

Interact with Document Content

The JavaScript Document object, and the objects it contains, allow programs to read, and sometimes interact with, portions of the document. It is not possible to read the actual text itself (although this will probably be possible in a future release of JavaScript) but, for example, it is possible to obtain a list of all hypertext links in a document.[4] In Navigator 3.0, it is even possible to use JavaScript to obtain an array of all images and Java applets embedded in a document.

[4] For important security reasons in Navigator 2.0 and 3.0, this is only true when the script reading the list of links (or other information) was loaded from the same web server as the page containing the links. Because of this security restriction, you currently cannot download an arbitrary page off the Web, and have JavaScript return you an array of the hypertext links on that page--i.e., you cannot write a web crawler in JavaScript. See Chapter 20, JavaScript Security, for a full discussion of this restriction and its resolution in a future version of JavaScript.

By far the most important capability for interacting with document contents is provided by the Form object, and by the Form element objects it can contain: the Button, Checkbox, Hidden, Password, Radio, Reset, Select, Submit, Text and Textarea elements. These element objects allow you to read and write the values of any input element in any form in the document. For example, the Internal Revenue Service could create a web page that contains a U.S. 1040EZ income tax return. When the user enters his filing status and gross income, JavaScript code could read the input, compute the appropriate personal exemption and standard deduction, subtract these values from the income, and fill in the result in the appropriate data field of the form. This technique is frequently seen in JavaScript calculator programs, which are common on the Web, and in fact, we'll see a tax calculator example, much like the one described above, a little later on in this chapter.

While HTML forms have traditionally be used only with CGI scripts, JavaScript is much more practical in some circumstances. Calculator programs like those described above are easy to implement with JavaScript, but would be impractical with CGI, because the server would have to be contacted to perform a computation every time the user entered a value or clicked on a button.

Another common use for the ability to read user input from form elements is for verification of a form before it is submitted. If client-side JavaScript is able to perform all necessary error checking of a user's input, then the required CGI script on the server side becomes much simpler, and no round trip to the server is necessary to detect and inform the user of the errors. Client-side JavaScript can also perform preprocessing of input data, which can reduce the amount of data that must be transmitted to the server. In some cases, client-side JavaScript can eliminate the need for CGI scripts on the server altogether! (On the other hand, JavaScript and CGI do work well together. For example, a CGI program can dynamically create JavaScript code "on the fly," just as it dynamically creates HTML.)

Interact with the User

An important feature of JavaScript is the ability to define "event handlers"--arbitrary pieces of code to be executed when a particular event occurs. Usually, these events are initiated by the user, when (for example) she moves the mouse over a hypertext link or enters a value in a form or clicks the Submit button in a form. This event-handling capability is a crucial one, because programming with graphical interfaces, such as HTML forms, inherently requires an event-driven model. JavaScript can trigger any kind of action in response to user events. Typical examples might be to display a special message in the status line when the user positions the mouse over a hypertext link, or to pop up a confirmation dialog box when the user submits an important form.

Read and Write Client State with Cookies

"Cookies" are Netscape's term for small amounts of state data stored permanently or temporarily by the client. They are transmitted back and forth to and from the server and allow a web page or web site to "remember" things about the client--for example, that the user has previously visited the site, or that they have already registered and obtained a password, or that they've expressed preferences about colors or layouts of web pages. Cookies help you provide the state information that is missing from the stateless HTTP protocol of the Web. The "My Yahoo!" site at http://my.yahoo.com/ is an excellent example of the use of cookies to remember a user's preferences.

When cookies were invented, they were intended for use exclusively by CGI scripts, and although stored on the client, they could only be read or written by the server. Their purpose was to allow CGI scripts to generate and send different HTML to the client depending on the value of the cookies. JavaScript changes this. JavaScript programs can read and write cookie values, and as we've noted above, they can dynamically generate HTML based on the value of cookies. The implications of this are subtle. CGI programming will still be an important technique in many cases that use cookies. In some cases, however, JavaScript can entirely replace the need for CGI.

Interact with Applets

In Navigator 3.0, JavaScript can interact with Java applets that are running in the browser. This important feature is part of Netscape's "LiveConnect", a communication layer that allows Java applets, Netscape plug-ins, and JavaScript code talk with and control one another. Using LiveConnect, JavaScript code can read and write properties of, and invoke methods of, Java applets and plug-ins. This capability is tremendously powerful, and truly allows JavaScript to "script" Java.

Manipulate Embedded Images

In Navigator 3.0, JavaScript can change the images displayed by an <IMG> tag. This allows sophisticated effects, such as having an image change when the mouse passes over it or when the user clicks on a button elsewhere in the browser. When Navigator 3.0 was released recently, this capability spawned a burst of creativity on web sites designed for the new browser.

Still More Features

In addition to all of the above, there are quite a few other JavaScript capabilities:

  • As mentioned at the start of this section, JavaScript can perform arbitrary computation. JavaScript has a floating-point data type, arithmetic operators that work with it, and a full complement of the standard floating-point mathematical functions.

  • The JavaScript Date object simplifies the process of computing and working with dates and times.

  • The Document object supports a property that specifies the "last modified" date for the current document. You can use it to automatically display a timestamp on any document.

  • JavaScript has a window.setTimeout() method that allows a block of arbitrary JavaScript code to be executed some number of milliseconds in the future. This is useful for building delays or repetitive actions into a JavaScript program.

  • The Navigator object (named after the web browser, of course) has variables that specify the name and version of the browser that is running, and also has variables that identify the platform it is running on. These variables allow scripts to customize their behavior based on browser or platform in order, for example, to take advantage of extra capabilities supported by some versions or to work around bugs that exist on some platforms.

  • In Navigator 3.0, JavaScript uses the navigator.plugins[] array to specify which "plug-ins" are installed in the browser; JavaScript uses the navigator.mimeTypes[] array to specify which MIME data formats are recognized by the browser.

  • In Navigator 3.0, the scroll() method of the Window object allows JavaScript programs to scroll windows in the X and Y dimensions.


Previous Home Next
JavaScript Myths Book Index What JavaScript Can't Do

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell