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
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
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
Figure 1.4 Server-side JavaScript during runtime
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:
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 simple, instance-based object model that still provides significant capabilities. 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.
Embedding JavaScript in HTML
You can embed JavaScript in an HTML document in the following ways:
<SCRIPT>
tag. See the following section, "Using the SCRIPT Tag".
<SCRIPT>
tag is an extension to HTML that can enclose any number of JavaScript statements as shown here:
<SCRIPT>A document can have multiple
JavaScript statements...
</SCRIPT>
<SCRIPT>
tags, and each can enclose any number of JavaScript statements.
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:
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 ...>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
<INPUT TYPE="button" onClick="doClick(this)" ...>
...
</FORM>
replace
method replaces the page.
<SCRIPT LANGUAGE="JavaScript1.2">Example 3. This example shows how to test the
// Replace this page in session history with the 1.2 version
location.replace("js1.2/mypage.html");
</SCRIPT>
[1.1-compatible page continues here...]
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]
<SCRIPT>Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending
<!-- Begin to hide script contents from old browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>
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.
Hello, net!
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
That's all, folks.
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>
This attribute is especially useful for sharing functions among many different pages.
The closing
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
...
</SCRIPT>
</HEAD>
<BODY>
...</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.
&
) and terminating it with a semicolon (;
). For example, you can include a greater-than symbol (>
) with the character entity >
and a less-than symbol (<
) with <
.
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
<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) {
Here's another example:
document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>")
}<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:
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>
The function
<SCRIPT>
document.write("The function returned ", square(5), ".");
</SCRIPT>
<P> All done.
</BODY>square
takes one argument, called number
. The function consists of one statement
that indicates to return the argument of the function multiplied by itself. The return number * number
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.
The
All done.
square
function used the line
to display output in Navigator. This line calls the document.write(...)
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>
The HEAD of this document defines two functions:
<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>
BODY
then calls the two functions to produce the display shown in Figure 1.7.
Figure 1.7 Display created using JavaScript functions
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>
If you load this URL into the web browser, it displays the following:
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>Hello, there.
If you choose View Document Source, the browser displays:
<HTML>
If you load
<BODY>
Hello,
there.
</BODY>
</HTML>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
onChange
event handler on each form element that you want validated.
onClick
event handler on the button that submits the form.
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>
This form submits the values to a page in a server-side JavaScript application called
<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>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
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,
<INPUT TYPE="submit"
When
onSubmit="return qty_check(theform.quantity, 0, 999)"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.
Last Updated: 10/31/97 10:34:02