JAVASCRIPT
Netscape

[About Javascript][Using the Script tag][Noscript]
[JavaScript entities][Functions][Using the Write method]
[Event handlers][Netscapes handbook]

About Javascript

JavaScript is Netscape's cross-platform, object-based scripting language for client and server applications. There are two types of JavaScript:

  • Navigator JavaScript, also called client-side JavaScript
  • LiveWire JavaScript, also called server-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.

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 (preferably within the HEAD tag).


Specifying the JavaScript version

The optional LANGUAGE attribute specifies the scripting language and JavaScript version:

<SCRIPT LANGUAGE="JavaScriptVersion">
    JavaScript statements. .
</SCRIPT>
JavaScriptVersion specifies one of the following to indicate which version of JavaScript your code is written for:

Navigator 2.0.:
<SCRIPT LANGUAGE="JavaScript">
Navigator 3.0.
<SCRIPT LANGUAGE="JavaScript1.1">

Statements within a <SCRIPT> tag are ignored if the user's browser does not have the level of JavaScript support specified in the LANGUAGE attribute.

For example:
Navigator 2.0 executes code within:
<SCRIPT LANGUAGE="JavaScript">
it ignores code within:
<SCRIPT LANGUAGE="JavaScript1.1"> .

If the LANGUAGE attribute is omitted,
Navigator 2.0 assumes LANGUAGE="JavaScript".
Navigator 3.0 assumes LANGUAGE="JavaScript1.1"

You can use the LANGUAGE attribute to write scripts that contain Navigator 3.0 features, and these scripts will not cause errors if run under Navigator 2.0. The following examples show some techniques for using the LANGUAGE attribute.

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:

<HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!--- Hide script from old browsers. document.write("Hello, net!") // End the hiding here. --> </SCRIPT> <P>That's all, folks. </BODY> </HTML>

This script 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.

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.

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://www.hiof.no/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 filename suffix to "application/x-javascript" MIME type, Navigator will not load the JavaScript file specified by the SRC attribute properly.

This requirement does not apply if you are using local files.

Script language examples

Example 1. This example shows how to use two separate versions of a JavaScript document, one for JavaScript 1.0 and one for JavaScript 1.1. The default document that loads is for JavaScript 1.0. If the user is running Navigator 3.0, the replace method replaces the page.

<SCRIPT LANGUAGE="JavaScript1.1">
// Replace this page in session 
// history with the 1.1 version
location.replace("js1.1/mypage.html")
</SCRIPT>
[1.0-compatible page continues here...]


Example 2. This example shows how to test the navigator.userAgent property to determine whether the user is running Navigator 3.0. The code then conditionally executes 1.1 features.

<SCRIPT LANGUAGE="JavaScript">
if (navigator.userAgent.indexOf("3.0") != -1)
   jsVersion = "1.1"
else
   jsVersion = "1.0"
</SCRIPT>

[hereafter, test jsVersion == "1.1" 
before use of any 1.1 extensions]

Noscript

Specifying alternate content

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 by choosing Network Preferences from the Options menu, 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://www.web.no/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 choosing Network Preferences from
the Options menu.
</NOSCRIPT>
...


JavaScript entities

Using JavaScript expressions
as HTML attribute values

Using JavaScript entities, you can specify a JavaScript expression as the value for 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:

<SCRIPT>
barWidth=50
</SCRIPT>

<HR WIDTH="&{barWidth};%" ALIGN="LEFT">
This would create the following display:


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 will be interpreted only on the right-hand side of HTML attribute name/value pairs. For example, <H4>&{myTitle};</H4> would display myTitle rather than the value of the variable myTitle.


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 function keyword.
  • A function name.
  • A comma-separated list of arguments to the function in parentheses.
  • The statements in the function in curly braces.
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.

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 script displays the following results:

The function returned 25.

All done.

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 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. A method is a function associated with an object.


Using the write method

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>

To see this output go here

The HEAD of this document defines two functions:

  • bar, which displays an HTML horizontal rule of a width specified by the function's argument.
  • output, which displays an HTML heading of the level specified by the first argument, heading text specified by the second argument, and paragraph text specified by the third argument.

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 twenty-five 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 3.0 prints output created with JavaScript. To print output, the user chooses Print from the File menu.

To view HTML code that was generated with JavaScript write and writeln methods, the user must specify the view-source: protocol. If the user chooses Document Source or Frame Source from the View menu, the content displayed is that of the wysiwyg: URL. The following example shows a view-source: URL:

view-source:wysiwyg://0/file:/c|/temp/genhtml.html
Navigator 2.0, does not print output created with JavaScript. For example, if the user chooses Print from the File menu to print the page in the previous example, you see only the line that reads "This is some standard HTML...," even though you see both lines onscreen.

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

  • A "subwindow" in a frame separately.
  • Form elements without reloading the page.


Scripting event handlers

JavaScript applications in the Navigator are largely event-driven. Events are actions that occur usually as a result of something the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a hyperlink. You can define event handlers, such as onChange and onClick, to make your script react to events.

Each event is recognized by certain objects (HTML tags), summarized in the following table:

EventApplies toOccurs whenEvent handler
abortimagesUser aborts the loading of an image (for example by clicking a link or clicking the Stop button)onAbort
blurwindows, frames, and all form elements User removes input focus from window, frame, or form elementonBlur
clickbuttons, radio buttons, checkboxes, submit buttons, reset buttons, links User clicks form element or linkonClick
changetext fields, textareas, select lists User changes value of elementonChange
errorimages, windowsThe loading of a document or image causes an error onError
focuswindows, frames, and all form elements User gives input focus to window, frame, or form elementonFocus
loaddocument body User loads the page in the NavigatoronLoad
mouseoutareas, links User moves mouse pointer out of an area (client-side image map) or linkonMouseout
mouseoverlinks User moves mouse pointer over a linkonMouse-Over
resetforms User resets a form (clicks a Reset button)onReset
selecttext fields, textareas User selects form element's input fieldonSelect
submitsubmit buttonUser submits a formonSubmit
unloaddocument bodyUser exits the pageonUnload

If an event applies to an HTML tag, then you can define an event handler for it. The name of an event handler is the name of the event, preceded by "on." For example, the event handler for the focus event is onFocus.

To create an event handler for an HTML tag, add an event handler attribute to the tag; Put JavaScript code in quotation marks as the attribute value. The general syntax is

<TAG eventHandler="JavaScript Code">
where TAG is an HTML tag and eventHandler is the name of the event handler.

For example, suppose you have created a JavaScript function called compute. You can cause Navigator to perform this function when the user clicks a button by assigning the function call to the button's onClick event handler:

<INPUT TYPE="button" VALUE="Calculate" 
onClick="compute(this.form)">
You can put any JavaScript statements inside the quotation marks following onClick. These statements are executed when the user clicks the button. If you want to include more than one statement, separate statements with a semicolon (;).

Notice in the preceding example this.form refers to the current form. The keyword this refers to the current object, which is the button. The construct this.form then refers to the form containing the button. The onClick event handler is a call to the compute function, with the current form as the argument.

In general, it is good practice to define functions for your event handlers:

  • It makes your code modular--you can use the same function as an event handler for many different items.
  • It makes your code easier to read.

Using quotation marks

Use single quotation marks ( ' ) to delimit string literals so that scripts can distinguish the literal from attribute values enclosed in double quotation marks. 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')">
Be sure to alternate double quotation marks with single quotation marks. Because event handlers in HTML must be enclosed in quotation marks, you must use single quotation marks to delimit string arguments. For example:

<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" 
    VALUE="Open Sesame!"
    onClick="window.open('mydoc.html', 
    'newWin')">
</FORM>

Example: using an event handler

In the following example, you can enter an expression (for example, 2 + 2) in the first text field, and then click the button. The second text field then displays the value of the expression (for example, 4).

<HEAD> <SCRIPT>
<!--- Hide script from old browsers
function compute(f) {
   if (confirm("Are you sure?"))
      f.result.value = eval(f.expr.value)
   else
      alert("Please come back again.")
}
// end hiding from old browsers -->
</SCRIPT> </HEAD>

<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" 
      onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
The display in Navigator will look like this:

Enter an expression:
Result:

The HEAD of the document defines a single function, compute, taking one argument, f, which is a Form object. The function uses the Navigator JavaScript method confirm to display a Confirm dialog box with OK and Cancel buttons.

If the user clicks OK, then confirm returns true, and the value of the result text field is set to the value of eval(f.expr.value). The built-in JavaScript function eval evaluates its argument, which can be any string representing any JavaScript expression or statements.

If the user clicks Cancel, then confirm returns false and the alert method displays another message.

The form contains a button with an onClick event handler that calls the compute function. When the user clicks the button, JavaScript calls compute with the argument this.form that denotes the current Form object. In compute, this form is referred to as the argument f.


Javascript handbook

To find more information about Javascript and how to use it, go to Netscapes Javascript Guide.

[Page][Font][Text Style ][Image][Table][Form][Applet][Frames]
[Marquee][Image Map][Javascript][Entities][Tag Index]