[Contents] [Previous] [Next] [Index]

Chapter 1
Getting Started

This chapter introduces JavaScript, discusses some of the fundamental concepts of JavaScript in Navigator and provides basic examples. It shows JavaScript code in action, so you can begin writing your own scripts immediately, using the example code as a starting point.

What is JavaScript?

JavaScript is Netscape's cross-platform, object-based scripting language for client and server applications. JavaScript lets you create applications that run over the Internet. Client applications run in a browser, such as Netscape Navigator, and server applications run on a server, such as Netscape Enterprise Server. Using JavaScript, you can create dynamic HTML pages that process user input and maintain persistent data using special objects, files, and relational databases. Through JavaScript's LiveConnect functionality, your applications can access Java and CORBA distributed-object applications.

Server-side and client-side JavaScript share the same core language. This core language corresponds to ECMA-262, the scripting language standardized by the European standards body, with some additions. The core language contains a set of core objects, such as the Array and Date objects. It also defines other language features such as its expressions, statements, and operators. Although server-side and client-side JavaScript use the same core functionality, in some cases they use them differently. You can download a PDF version of the ECMA-262 specification.

The components of JavaScript are illustrated in Figure 1.1.

Figure 1.1    The JavaScript language

Client-side JavaScript (or Navigator JavaScript) encompasses the core language plus extras such as the predefined objects only relevant to running JavaScript in a browser. Server-side JavaScript encompasses the same core language plus extras such as the predefined objects and functions only relevant to running JavaScript on a server. This guide provides information and instructions for using the core and client-side JavaScript.

Client-side JavaScript is embedded directly in HTML pages and is interpreted by the browser completely at runtime. Because production applications frequently have greater performance demands upon them, JavaScript applications that take advantage of its server-side capabilities are compiled before they are deployed. The next two sections introduce you to the workings of JavaScript on the client and on the server.

JavaScript in Navigator

Web browsers such as Netscape Navigator 2.0 (and later versions) can interpret client-side JavaScript statements embedded in an HTML page. When the browser (or client) requests such a page, the server sends the full content of the document, including HTML and JavaScript statements, over the network to the client. The client reads the page from top to bottom, displaying the results of the HTML and executing JavaScript statements as it goes. This process, illustrated in Figure 1.2, produces the results that the user sees.

Figure 1.2    Client-side JavaScript

Client-side JavaScript statements embedded in an HTML page can respond to user events such as mouse-clicks, form input, and page navigation. For example, you can write a JavaScript function to verify that users enter valid information into a form requesting a telephone number or zip code. Without any network transmission, the HTML page with embedded JavaScript can check the entered data and alert the user with a dialog box if the input is invalid.

JavaScript on the Server

In general, this book does not discuss server-side JavaScript. However, this section gives a very brief overview of how server-side JavaScript applications work. For more detailed information, see Writing Server-Side JavaScript Applications.

On the server, you also embed JavaScript in HTML pages. The server-side statements can connect to relational databases from different vendors, share information across users of an application, access the file system on the server, or communicate with other applications through LiveConnect and Java. HTML pages with server-side JavaScript can also include client-side JavaScript.

In contrast to pure client-side JavaScript scripts, HTML pages that use server-side JavaScript are compiled into bytecode executable files. These application executables are run in concert with a Web server that contains the JavaScript runtime engine. This makes creating JavaScript applications a two-stage process.

In the first stage, shown in Figure 1.3, you (the developer) create HTML pages (which can contain both client-side and server-side JavaScript statements) and JavaScript files. You then compile all of those files into a single executable.

Figure 1.3    Server-side JavaScript during development

In the second stage, shown in Figure 1.4, a client browser requests a page that was compiled into the application. The runtime engine finds the compiled representation of that page in the executable, runs any server-side JavaScript statements found on the page, and dynamically generates the HTML page to return. The result of executing server-side JavaScript statements might add new HTML or client-side JavaScript statements to the original HTML page. The runtime engine then sends the newly generated page over the network to the Navigator client, which runs any client-side JavaScript and displays the results.

Figure 1.4    Server-side JavaScript during runtime

In contrast to standard CGI programs, all JavaScript source is integrated directly into HTML pages, facilitating rapid development and easy maintenance. Server-side JavaScript's Session Management Service contains objects you can use to maintain data that persists across client requests, multiple clients, and multiple applications. Server-side JavaScript's LiveWire Database Service provides objects for database access that serve as an interface to Structured Query Language (SQL) database servers.

JavaScript, the Core Language

As described in the previous sections, client-side and server-side JavaScript differ in numerous ways, but they have the following elements in common:

Different versions of JavaScript work with specific versions of Navigator. For example, JavaScript 1.2 is for Navigator 4.0. Some features available in JavaScript 1.2 are not available in JavaScript 1.1 and hence are not available in Navigator 3.0. For information see "Specifying the JavaScript Version".

Part 2, "The Core JavaScript Language", describes the common features of client and server JavaScript.

JavaScript and Java

JavaScript and Java are similar in some ways but fundamentally different in others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript supports most Java expression syntax and basic control-flow constructs. In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.

Java is an object-oriented programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's object-oriented model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript authoring.

In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.

Table 1.1  JavaScript compared to Java
JavaScript Java
Interpreted (not compiled) by client.

Compiled bytecodes downloaded from server, executed on client.

Object-based. No distinction between types of objects. Inheritance is through the prototype mechanism and properties and methods can be added to any object dynamically.

Object-oriented. Objects are divided into classes and instances with all inheritance through the class hieararchy. Classes and instances cannot have properties or methods added dynamically.

Code integrated with, and embedded in, HTML.

Applets distinct from HTML (accessed from HTML pages).

Variable data types not declared (loose typing).

Variable data types must be declared (strong typing).

Dynamic binding. Object references checked at runtime.

Static binding. Object references must exist at compile-time.

Cannot automatically write to hard disk.

Cannot automatically write to hard disk.

Embedding JavaScript in HTML

You can embed JavaScript in an HTML document in the following ways:

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:

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

Specifying the JavaScript Version

As JavaScript evolves along with Navigator, its capabilities expand greatly. This means that JavaScript written for Navigator 4.0 may not work in earlier versions of Navigator. To ensure that users of earlier versions of Navigator avoid problems when viewing pages that use JavaScript 1.2, use the LANGUAGE attribute in the <SCRIPT> tag to indicate which version of JavaScript you're using.

Statements within a <SCRIPT> tag are ignored if the browser does not have the level of JavaScript support specified in the LANGUAGE attribute; for example:

By using the LANGUAGE attribute, you can write general JavaScript that Navigator version 2.0 and higher recognize, and include additional or refined behavior for newer versions of Navigator.

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.

<SCRIPT LANGUAGE="JavaScript">
// Define 1.0-compatible functions such as doClick() here
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.1">
// Redefine those functions using 1.1 features
// Also define 1.1-only functions
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript1.2">
// Redefine those functions using 1.2 features
// Also define 1.2-only functions
</SCRIPT>
<FORM ...>
<INPUT TYPE="button" onClick="doClick(this)" ...>
...
</FORM>
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
location.replace("js1.2/mypage.html");
</SCRIPT>
[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.

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

Hiding Scripts within Comment Tags

Only Netscape 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:

<SCRIPT>
<!-- Begin to hide script contents from old browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>
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 don't 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 1.5 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 1.5    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 2, "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:

<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
...
</SCRIPT>
</HEAD>
<BODY>
...
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 unless the inclusion has an error. For example, you might want to put the following statement between the <SCRIPT SRC="..."> and </SCRIPT> statements:

document.write("Included JS file not found");
The SRC attribute can specify any URL, relative or absolute. For example:

<SCRIPT SRC="http://home.netscape.com/functions/jsfuncs.js">
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 Figure 1.6.

Figure 1.6    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:

<H4>&{myTitle};</H4>
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.

<NOSCRIPT>
<B>This page uses JavaScript, so you need to get Netscape Navigator 2.0
or later!
<BR>
<A HREF="http://home.netscape.com/comprod/mirror/index.html">
<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.
</NOSCRIPT>
...

Defining and Calling Functions

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure--a set of statements that performs a specific task. A function definition has these basic parts:

It's important to understand the difference between defining and calling a function. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters.

Generally, you should define the functions for a page in the HEAD portion of a document. That way, all functions are defined before any content is displayed. Otherwise, the user might perform an action while the page is still loading that triggers an event handler and calls an undefined function, leading to an error. (Event handlers are introduced in Chapter 2, "Handling Events.")

The following example defines a simple function in the HEAD of a document and then calls it in the BODY of the document:

<HEAD> 
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers
function square(number) {
   return number * number;
}
// End script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
   document.write("The function returned ", square(5), ".");
</SCRIPT>
<P> All done.
</BODY>
The function square takes one argument, called number. The function consists of one statement

return number * number
that indicates to return the argument of the function multiplied by itself. The return statement specifies the value returned by the function. In the BODY of the document, the statement

square(5)
calls the function with an argument of five. The function executes its statements and returns the value twenty-five. The script displays the following results:

The function returned 25.
All done.
The square function used the line

document.write(...)
to display output in Navigator. This line calls the write method of the Navigator document object with JavaScript's standard object notation:

objectName.methodName(arguments...)
where objectName is the name of the object, methodName is the name of the method, and arguments is a list of arguments to the method, separated by commas.

In addition to defining functions as described here, you can also define Function objects, as described in "Function Object". For a complete description of defining and calling functions, see "Functions".

A method is a function associated with an object. You'll learn more about objects and methods in Chapter 10, "Object Model." But right now, we will explore write a little more, because it is particularly useful.

Using the Write Method

As you saw in the previous example, the write method of document displays output in the Navigator. "Big deal," you say, "HTML already does that." But in a script you can do all kinds of things you can't do with ordinary HTML. For example, you can display text conditionally or based on variable arguments. For these reasons, write is one of the most often-used JavaScript methods.

The write method takes any number of string arguments that can be string literals or variables. You can also use the string concatenation operator (+) to create one string from several when using write.

Consider the following script, which generates dynamic HTML with Navigator JavaScript:

<HEAD> 
<SCRIPT>
<!--- Hide script from old browsers
// This function displays a horizontal bar of specified width
function bar(widthPct) {
   document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>");
}
// This function displays a heading of specified level and some text
function output(headLevel, headText, text) {
   document.write("<H", headLevel, ">", headText, "</H",
      headLevel, "><P>", text)
}
// end script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
<!--- hide script from old browsers
bar(25)
output(2, "JavaScript Rules!", "Using JavaScript is easy...")
// end script hiding from old browsers -->
</SCRIPT>
<P> This is some standard HTML, unlike the above that is generated.
</BODY>
The HEAD of this document defines two functions:

The document BODY then calls the two functions to produce the display shown in Figure 1.7.

Figure 1.7    Display created using JavaScript functions

The following line creates the output of the bar function:

document.write("<HR ALIGN='left' WIDTH=", widthPct, "%>")
Notice that the definition of bar uses single quotation marks inside double quotation marks. You must do this whenever you want to indicate a quoted string inside a string literal. Then the call to bar with an argument of 25 produces output equivalent to the following HTML:

<HR ALIGN="left" WIDTH=25%>
write has a companion method, writeln, which adds a newline sequence (a carriage return or a carriage return and linefeed, depending on the platform) at the end of its output. Because HTML generally ignores newlines, there is no difference between write and writeln except inside tags such as PRE, which respect carriage returns.

Printing Output

Navigator versions 3.0 and higher print output created with JavaScript. To print output, the user chooses Print from the File menu. Navigator 2.0 does not print output created with JavaScript.

In Navigator 4.0, if you print a page that contains layers, each layer is printed separately on the same page. For example, if three layers overlap each other in the browser, the printed page shows each layers separately.

If you choose Document Source or Frame Source from the View menu, the web browser displays the content of the HTML file with the generated HTML. If you instead want to view the HTML source showing the scripts which generate HTML (with the document.write and document.writeln methods), do not use the Document Source or Frame Source menu item. In this situation, use the view-source: protocol. For example, assume the file file://c|/test.html contains this text:

<HTML>
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>
If you load this URL into the web browser, it displays the following:

Hello, there.
If you choose View Document Source, the browser displays:

<HTML>
<BODY>
Hello,
 there.
</BODY>
</HTML>
If you load view-source:file://c|/test.html, the browser displays:

<HTML>
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>

Displaying Output

JavaScript in Navigator generates its results from the top of the page down. Once text has been displayed, you cannot change it without reloading the page. In general, you cannot update part of a page without updating the entire page. However, you can update

Validating Form Input

One of the most important uses of JavaScript is to validate form input to server-based programs such as server-side JavaScript applications or CGI programs. This is useful because

Generally, you'll want to validate input in (at least) two places:

The JavaScript page on DevEdge contains pointers to sample code. One such pointer is a complete set of form validation functions. This section presents some simple examples, but you should check out the samples on DevEdge.

Example Validation Functions

The following are some simple validation functions.

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function isaPosNum(s) {
   return (parseInt(s) > 0)
}
function qty_check(item, min, max) {
   var returnVal = false
   if (!isaPosNum(item.value))
      alert("Please enter a positive number")
   else if (parseInt(item.value) < min)
      alert("Please enter a " + item.name + " greater than " + min)
   else if (parseInt(item.value) > max)
      alert("Please enter a " + item.name + " less than " + max)
   else
      returnVal = true
   return returnVal
}
function validateAndSubmit(theform) {
   if (qty_check(theform.quantity, 0, 999)) {
      alert("Order has been Submitted")
      return true
   }
   else {
      alert("Sorry, Order Cannot Be Submitted!")
      return false
   }
}
</SCRIPT>
</HEAD>
isaPosNum is a simple function that returns true if its argument is a positive number, and false otherwise.

qty_check takes three arguments: an object corresponding to the form element being validated (item) and the minimum and maximum allowable values for the item (min and max). It checks that the value of item is a number between min and max and displays an alert if it is not.

validateAndSubmit takes a Form object as its argument; it uses qty_check to check the value of the form element and submits the form if the input value is valid. Otherwise, it displays an alert and does not submit the form.

Using the Validation Functions

In this example, the BODY of the document uses qty_check as an onChange event handler for a text field and validateAndSubmit as the onClick event handler for a button.

<BODY>
<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post">
How many widgets today?
<INPUT TYPE="text" NAME="quantity" onChange="qty_check(this, 0, 999)">
<BR>
<INPUT TYPE="button" VALUE="Enter Order" onClick="validateAndSubmit(this.form)">
</FORM>
</BODY>
This form submits the values to a page in a server-side JavaScript application called lwapp.html. It also could be used to submit the form to a CGI program. The form is shown in Figure 1.8.

Figure 1.8    A JavaScript form

The onChange event handler is triggered when you change the value in the text field and move focus from the field by either pressing the Tab key or clicking the mouse outside the field. Notice that both event handlers use this to represent the current object: in the text field, it is used to pass the JavaScript object corresponding to the text field to qty_check, and in the button it is used to pass the JavaScript Form object to validateAndSubmit.

To submit the form to the server-based program, this example uses a button that calls validateAndSubmit, which submits the form using the submit method, if the data are valid. You can also use a submit button (defined by <INPUT TYPE="submit">) with an onSubmit event handler that returns false if the data are not valid. For example,

<FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post" 
   onSubmit="return qty_check(theform.quantity, 0, 999)">
...
<INPUT TYPE="submit">
...
</FORM>
When qty_check returns false if the data are invalid, the onSubmit handler will prohibit the form from being submitted.

Debugging JavaScript

JavaScript allows you to write complex computer programs. As with all languages, you may make mistakes while writing your scripts. The Netscape JavaScript Debugger allows you to debug your JavaScript scripts.

For information on using the debugger, see Getting Started with Netscape JavaScript Debugger.


[Contents] [Previous] [Next] [Index]

Last Updated: 11/26/97 09:25:26


Copyright © 1997 Netscape Communications Corporation