[Chapter 13] 13.3 JavaScript
Author: Chuck Musciano and Bill Kennedy
Date: Fri Sep 5 13:30:04 1997

#

| Chapter 13 Executable Content |

## 13.3 JavaScript

Whether `<applet>`, `<object>`, or `<embed>`, all the executable content we've talked about so far have had one common trait: they are separate from the browser and the HTML document--separate data, separate execution engine.

JavaScript is different. It is a scripting language that taps the native functionality of the browser. You may sprinkle JavaScript statements throughout your documents, either as blocks of code or single statements attached to individual tags. The JavaScript-enabled browsers, including both Netscape and Internet Explorer, interpret and act upon the JavaScript statements you provide to do such things as alter the appearance of the document, control the display, validate and manipulate form elements, and perform general computational tasks.

Like with Java, we will not pretend to teach JavaScript programming in this book. We'll show you how to embed and execute JavaScript within your documents, and ask that you turn to books like JavaScript: The Definitive Guide, from O'Reilly, for a complete definition of the JavaScript language.

### The `<script>` Tag

One way to place JavaScript code in your document is via the `<script>` tag.

Everything between the `<script>` and `</script>` tags is processed by the browser as executable JavaScript statements and data. You cannot place HTML within this tag; it will flagged as an error by the browser.

Browsers that do not support the `<script>` tag will process contents of the tag as regular HTML, to the confusion of the user. For this reason, and as with the new `<style>` tag, we recommend that you include the contents of the `<script>` tag inside HTML comments:

    <script language="JavaScript">
    <!--
       JavaScript statements go here
    // -->
    </script>

For browsers that ignore the `<script>` tag, the contents are masked by the HTML comments delimiters `<!-- and -->`. JavaScript-enabled browsers, on the other hand, automatically recognize and interpret the JavaScript statements delimited by the comment tags. By using this skeleton for all your `<script>` tags, you can be sure that all browsers will handle your document gracefully, if not completely.

You may include more than one `<script>` tag in a document, located in either the `<head>` or the `<body>`. The JavaScript-enabled browser executes the statements in order as they occur. Variables and functions defined within one `<script>` tag may be referenced by JavaScript statements in other `<script>` tags. In fact, one common JavaScript programming style is to use a single `<script>` in the document `<head>` to define common functions and global variables for the document, and then to call those functions and reference their variables in other JavaScript statements sprinkled throughout the document.

#### The language attribute

Use the language attribute in the `<script>` tag to declare the scripting language you used to compose the contents of the tag. If you are using JavaScript--by far the most common HTML scripting language on the Web--set this attribute's value to JavaScript. You may occasionally see the language value VBScript, indicating that the enclosed code is written in Microsoft's Visual Basic Script.

With JavaScript, you may also use the value "JavaScript 1.1", indicating that the enclosed script is to be processed only by Netscape 3.0 or later. Netscape 2.0, which supports JavaScript 1.0, will not process scripts identified as "JavaScript 1.1".

#### The src attribute

For particularly large JavaScript programs, you might want to store the code in a separate file. In these cases, have the browser load that separate file through the src attribute. The value of the src attribute is the URL of the file containing the JavaScript program. The stored file should have a MIME type of application/x-javascript; but will also be properly handled automatically by the server if the filename suffix is .js.

For example,

    <script language=JavaScript src="http://www.kumquat.com/quatscript.js">
    </script>

tells the `<script>`-able browser to load a JavaScript program called quatscript.js from the server. Even though there are no `<script>` contents, the ending `</script>` is still required.

### The `<noscript>` Tag

So that you can tell users of browsers that do not support the `<script>` tag that they are missing something, Netscape supports the `<noscript>` tag.

Unfortunately, only Netscape 3.0 and later versions ignore the contents of the `<noscript>` tag. So even `<script>`-able browsers like Internet Explorer and Netscape 2.0 will display the contents of the `<noscript>` tag, to the confusion of their users.

JavaScript event handlers

So, in reality, the `<noscript>` tag has limited usefulness due to its inconsistent support among browsers. There are other ways to detect and handle `<script>`-challenged browsers, detailed in any good JavaScript book.

### JavaScript Event Handlers

One of the most important features provided by JavaScript is the ability to detect and react to events that occur while a document is loaded, rendered, and used. The JavaScript code that handles these events may be placed within the `<script>` tag, but more commonly it is associated with a specific tag via one or more special tag attributes.

For example, you might want to invoke a JavaScript functions when the user passes the mouse over a hyperlink in a document. The JavaScript-aware browsers support a special "mouse over" event-handler attribute for the `<a>` tag called onMouseOver to do just that:

    <a href=doc.html onMouseOver="document.status='Click me!'; return true">

When the mouse passes over this example link, the browser executes the JavaScript statements. (Notice that the two JavaScript statements are enclosed in quotes and separated by a semi-colon, and that single quotes surround the text-message portion of the first statement.)

While a complete explanation of this code is beyond our scope, the net result is that the browser places the message "Click me!" in the status bar of the browser window. Commonly, HTML authors use this simple JavaScript function to display a more descriptive explanation of a hyperlink, in place of the often cryptic URL which the browser traditionally displays in the status window.

The value of any of the JavaScript event handler attributes is a quoted string containing one or more JavaScript statements, separated by semicolons. Extremely long statements can be broken across several lines, if needed. Care should also be taken in using entities for embedded double quotes in the statements, to avoid a syntax error when processing the attribute value.

We list the various JavaScript event handlers and their associated tags in Table 13.1, along with the section of this book that describes them in more detail.

Table 13.1: JavaScript event handlers and their supporting HTML tags
Event Handlers | HTML Tags | See section
--- | --- | ---
onAbort | `<img>` | 5.2.6.14
onBlur | `<body>` `<frameset>` `<input>` `<select>` `<textarea>` | 12.3.1.3 12.3.1.3 10.2.9 10.4.1.3 10.3.3
onChange | `<input>` `<select>` `<textarea>` | 10.2.9 10.4.1.3 10.3.3
onClick | `<a>` `<input>` `<select>` | 7.3.1.4 10.2.9 10.4.1.3
onError | `<img>` | 5.2.6.14
onFocus | `<body>` `<frameset>` `<input>` `<select>` `<textarea>` | 12.3.1.3 12.3.1.3 10.2.9 10.4.1.3 10.3.3
onLoad | `<body>` `<frameset>` `<img>` | 12.3.1.3 12.3.1.3 5.2.6.14
onMouseOut | `<a>` `<area>` | 7.3.1.4 7.5.4.6
onMouseOver | `<a>` `<area>` | 7.3.1.4 7.5.4.6
onReset | `<form>` | 10.1.1.9
onSelect | `<input>` `<textarea>` | 10.2.9 10.3.3
onSubmit | `<form>` | 10.1.1.9
onUnload | `<body>` `<frameset>` | 12.3.1.3 12.3.1.3

### JavaScript URLs

You can replace any conventional URL reference in a document with one or more JavaScript statements. The browser then executes the JavaScript code, rather than download another document, whenever the browser references the URL. The result of the last statement is taken to be the "document" referenced by the URL and is displayed by the browser accordingly. The result of the last statement is not the URL of a document; it is the actual content to be displayed by the browser.

To create a JavaScript URL, use javascript as the URL's protocol:

    <a href="javascript:generate_document()">

In the example, the JavaScript function generate_document() gets executed whenever the hyperlink gets selected by the user. The value returned by the function, presumably a valid HTML document, is rendered and displayed by the browser.

It may be that the executed statement returns no value. In these cases, the current document is left unchanged. For example, this JavaScript URL:

    <a href="javascript:alert('Error!')">

pops up an alert dialog box, and does nothing else. The document containing the hyperlink would still be visible after the dialog box gets displayed and is dismissed by the user.

### JavaScript Entities

Character entities in HTML consist of an ampersand, an entity name or number, and a closing semicolon. They are used to insert special or reserved characters into documents.

Similarly, JavaScript entities consist of an ampersand, one or more JavaScript statements enclosed in curly braces, and a closing semicolon. For example:

    &{document.fgColor};

More than one statement must be separated by semicolons within the curly braces. The value of the last (or only) statement is converted to a string and replaces the entity in the document.

Normally, HTML entities can appear anywhere in a document. JavaScript entities are restricted to being values of tag attributes. This lets you write "dynamic tags" whose attributes are not known until the document is loaded and the JavaScript executed. For example,

    <body text=&{favorite_color()};>

will set the text color of the document to the color value returned by the individual's favorite_color() function.

### The `<server>` Tag

The `<server>` tag is a strange beast. It is processed by the web server, and never seen by the browser. So what you can do with this tag depends on the server you are using, not the reader's browser. The Netscape server uses the `<server>` tag to let you to place JavaScript statements within an HTML document that get processed by the server. The result of executing these statements is inserted into the document, replacing the `<server>` tag. A complete discussion of this so-called "server-side" JavaScript is completely beyond this book; we include this brief reference only to document the `<server>` tag.

Like the `<script>` tag, the `<server>` tag contains JavaScript code. However, the latter tag and content code must appear inside the document `<head>`, not elsewhere. It is extracted from the document and executed by the server when the document is requested for download.

JavaScript style sheets

Obviously, server-side JavaScript is tightly coupled to your server. To fully exploit this tag and the benefits of server-side JavaScript or other server-side programming languages, consult your web server's documentation for complete details.

Embedded Content |  | JavaScript Style Sheets