Table of Contents | Previous | Next | Index

Chapter 9
Embedding JavaScript in HTML

You can embed JavaScript in an HTML document as statements and functions within a <SCRIPT> tag, by specifying a file as the JavaScript source, by specifying a JavaScript expression as the value of an HTML attribute, or as event handlers within certain other HTML tags (primarily form elements).

This chapter contains the following sections:

For information on scripting with event handlers, see Chapter 10, "Handling Events."

NOTE: Unlike HTML, JavaScript is case sensitive.

Using the SCRIPT Tag

The <SCRIPT> tag is an extension to HTML that can enclose any number of JavaScript statements as shown here:

   JavaScript statements...
A document can have multiple <SCRIPT> tags, and each can enclose any number of JavaScript statements.

Specifying the JavaScript Version

Each version of Navigator supports a different version of JavaScript. To ensure that users of various versions of Navigator avoid problems when viewing pages that use JavaScript, use the LANGUAGE attribute of the <SCRIPT> tag to specify the version of JavaScript with which a script complies. For example, to use JavaScript 1.2 syntax, you specify the following:

<SCRIPT LANGUAGE="JavaScript1.2">
Using the LANGUAGE tag attribute, you can write scripts compliant with earlier versions of Navigator. You can write different scripts for the different versions of the browser. If the specific browser does not support the specified JavaScript version, the code is ignored. If you do not specify a LANGUAGE attribute, the default behavior depends on the Navigator version.

The following table lists the <SCRIPT> tags supported by different Netscape versions.

Table 9.1 JavaScript and Navigator versions
Navigator version Default JavaScript version <SCRIPT> tags supported

Navigator earlier than 2.0

JavaScript not supported


Navigator 2.0

JavaScript 1.0


Navigator 3.0

JavaScript 1.1

<SCRIPT LANGUAGE="JavaScript1.1"> and all earlier versions

Navigator 4.0-4.05

JavaScript 1.2

<SCRIPT LANGUAGE="JavaScript1.2"> and all earlier versions

Navigator 4.06-4.5

JavaScript 1.3

<SCRIPT LANGUAGE="JavaScript1.3"> and all earlier versions

Navigator ignores code within <SCRIPT> tags that specify an unsupported version. For example, Navigator 3.0 does not support JavaScript 1.2, so if a user runs a JavaScript 1.2 script in Navigator 3.0, the script is ignored.

Example 1. This example shows how to define functions three times, once for JavaScript 1.0, once using JavaScript 1.1 features, and a third time using JavaScript 1.2 features.

// Define 1.0-compatible functions such as doClick() here
<SCRIPT LANGUAGE="JavaScript1.1">
// Redefine those functions using 1.1 features
// Also define 1.1-only functions
<SCRIPT LANGUAGE="JavaScript1.2">
// Redefine those functions using 1.2 features
// Also define 1.2-only functions
<FORM ...>
<INPUT TYPE="button" onClick="doClick(this)" ...>
Example 2. This example shows how to use two separate versions of a JavaScript document, one for JavaScript 1.1 and one for JavaScript 1.2. The default document that loads is for JavaScript 1.1. If the user is running Navigator 4.0, the replace method replaces the page.

<SCRIPT LANGUAGE="JavaScript1.2">
// Replace this page in session history with the 1.2 version
[1.1-compatible page continues here...]
Example 3. This example shows how to test the navigator.userAgent property to determine which version of Navigator 4.0 is running. The code then conditionally executes 1.1 and 1.2 features.

if (navigator.userAgent.indexOf("4.0") != -1)
   jsVersion = "1.2";
else if (navigator.userAgent.indexOf("3.0") != -1)
   jsVersion = "1.1";
   jsVersion = "1.0";
[hereafter, test jsVersion before use of any 1.1 or 1.2 extensions]

Hiding Scripts Within Comment Tags

Only Navigator versions 2.0 and later recognize JavaScript. To ensure that other browsers ignore JavaScript code, place the entire script within HTML comment tags, and precede the ending comment tag with a double-slash (//) that indicates a JavaScript single-line comment:

<!-- Begin to hide script contents from old browsers.
JavaScript statements...
// End the hiding here. -->
Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending SCRIPT tags. All the script statements in between are enclosed in an HTML comment, so they are ignored too. Navigator properly interprets the SCRIPT tags and ignores the line in the script beginning with the double-slash (//).

Although you are not required to use this technique, it is considered good etiquette so that your pages do not generate unformatted script statements for those not using Navigator 2.0 or later.

NOTE: For simplicity, some of the examples in this book do not hide scripts.

Example: a First Script

Figure 9.1 shows a simple script that displays the following in Navigator:

Hello, net!
That's all, folks.

Notice that there is no difference in appearance between the first line, generated with JavaScript, and the second line, generated with plain HTML.

Figure 9.1   A simple script

You may sometimes see a semicolon at the end of each line of JavaScript. In general, semicolons are optional and are required only if you want to put more than one statement on a single line. This is most useful in defining event handlers, which are discussed in Chapter 10, "Handling Events."

Specifying a File of JavaScript Code

The SRC attribute of the <SCRIPT> tag lets you specify a file as the JavaScript source (rather than embedding the JavaScript in the HTML). For example:

<SCRIPT SRC="common.js">
This attribute is especially useful for sharing functions among many different pages.

The closing </SCRIPT> tag is required.

JavaScript statements within a <SCRIPT> tag with a SRC attribute are ignored except by browsers that do not support the SRC attribute, such as Navigator 2.

URLs the SRC Attribute Can Specify

The SRC attribute can specify any URL, relative or absolute. For example:

If you load a document with any URL other than a file: URL, and that document itself contains a <SCRIPT SRC="..."> tag, the internal SRC attribute cannot refer to another file: URL.

Requirements for Files Specified by the SRC Attribute

External JavaScript files cannot contain any HTML tags: they must contain only JavaScript statements and function definitions.

External JavaScript files should have the file name suffix .js, and the server must map the .js suffix to the MIME type application/x-javascript, which the server sends back in the HTTP header. To map the suffix to the MIME type, add the following line to the mime.types file in the server's config directory, and then restart the server.

type=application/x-javascript   exts=js
If the server does not map the .js suffix to the application/x-javascript MIME type, Navigator improperly loads the JavaScript file specified by the SRC attribute.

NOTE: This requirement does not apply if you use local files.

Using JavaScript Expressions as HTML Attribute Values

Using JavaScript entities, you can specify a JavaScript expression as the value of an HTML attribute. Entity values are evaluated dynamically. This allows you to create more flexible HTML constructs, because the attributes of one HTML element can depend on information about elements placed previously on the page.

You may already be familiar with HTML character entities by which you can define characters with special numerical codes or names by preceding the name with an ampersand (&) and terminating it with a semicolon (;). For example, you can include a greater-than symbol (>) with the character entity &GT; and a less-than symbol (<) with &LT;.

JavaScript entities also start with an ampersand (&) and end with a semicolon (;). Instead of a name or number, you use a JavaScript expression enclosed in curly braces {}. You can use JavaScript entities only where an HTML attribute value would normally go. For example, suppose you define a variable barWidth. You could create a horizontal rule with the specified percentage width as follows:

<HR WIDTH="&{barWidth};%" ALIGN="LEFT">
So, for example, if barWidth were 50, this statement would create the display shown in the following figure.

Figure 9.2   Display created using JavaScript entity

As with other HTML, after layout has occurred, the display of a page can change only if you reload the page.

Unlike regular entities which can appear anywhere in the HTML text flow, JavaScript entities are interpreted only on the right-hand side of HTML attribute name/value pairs. For example, if you have this statement:

It displays the string myTitle rather than the value of the variable myTitle.

Using Quotation Marks

Whenever you want to indicate a quoted string inside a string literal, use single quotation marks (') to delimit the string literal. This allows the script to distinguish the literal inside the string. In the following example, the function bar contains the literal "left" within a double-quoted attribute value:

function bar(widthPct) {
   document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>")
Here's another example:

<INPUT TYPE="button" VALUE="Press Me" onClick="myfunc('astring')">

Specifying Alternate Content with the NOSCRIPT Tag

Use the <NOSCRIPT> tag to specify alternate content for browsers that do not support JavaScript. HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not support JavaScript; code within the tag is ignored by Navigator. Note however, that if the user has disabled JavaScript from the Advanced tab of the Preferences dialog, Navigator displays the code within the <NOSCRIPT> tag.

The following example shows a <NOSCRIPT> tag.

<B>This page uses JavaScript, so you need to get Netscape Navigator 2.0
or later!
<A HREF="">
<IMG SRC="NSNow.gif"></A>
If you are using Navigator 2.0 or later, and you see this message,
you should enable JavaScript by on the Advanced page of the
Preferences dialog box.

Table of Contents | Previous | Next | Index

Last Updated: 05/27/99 21:21:33

Copyright (c) 1999 Netscape Communications Corporation

Any sample code included above is provided for your use on an "AS IS" basis, under the Netscape License Agreement - Terms of Use