[Access to Wang masthead]

Using Script Languages

Part 3: JavaScript

From "VS & Beyond",  Access to Wang, March 1998
  [ Prior Article ]     [ Return to the Catalog of articles ]     [ Next Article ]  

This month we'll examine JavaScript, a client-side scripting language for Web browsers and servers. JavaScript is widely used in commercial and educational web sites to animate navigational buttons (images that change as your roll over them with the mouse pointer), to check user entry and calculate total amounts on forms, and to tailor web page results according to specific characteristics of the user's viewing environment. More complex tasks performed by JavaScript include the identification of browser types and capabilities (including the Plug-Ins used by Netscape browsers), the use of small databases, creating and using cookies, and advanced forms control. You've probably also seen script errors on sites that use JavaScript - more on those issues below.

JavaScript was developed by Netscape to enhance the capabilities of its version 2.0 browser. Originally it was known as LiveScript, and some very old browsers still require that it be identified by that name within web pages. Like VBScript, JavaScript is normally run at the client level (e.g. embedded within a web page) but it can also be used to script server activities. Since its origins at Netscape many of its features have been adopted (and, unfortunately, adapted) by Microsoft into a browser script language known as JScript.

Operating environments

JavaScript is typically embedded within a HTML file for a Web application, though it can also be used to create server applications on some server products. The script's code is interpreted and executed at the client side, using programs within the user's browser. This approach allows developers to build and distribute sophisticated applications without creating specific program files for every computer platform, but it relies on the compatibility and functionality of the local system and software to work correctly.

Like VBScript, JavaScript uses the <SCRIPT>...</NOSCRIPT> tags to hide the script code from browsers that can't use it. In addition to these tags, it is also necessary to use specific comment tags (as shown in Figure One, below) to make sure the scripts are ignored. It is sometimes necessary to take even more steps to ensure you get the correct results (or at least no script errors!); these are described in more detail in the documentation listed in the References section, below. (Naturally, browsers that skip the script code also do not receive the benefits of these scripts - an important design consideration.)

In spite of its wide use, there are some important compatibility issues to be weighed before considering JavaScript. Primary among these is JavaScript's own volatility, having veered in capabilities and syntax over the three generations of its existence. Worse, there are some important differences between the implementations of Netscape and Microsoft that make in necessary to use only those features in common between both manufacturers.

Language model

Like VBScript and many other application languages, JavaScript scripts use a paradigm of objects that interact with each other and with the events that occur through the actions provided by functions. Objects also have properties (characteristics, parameters) and methods (functions associated with an object). Commonly-used objects include:

These "building blocks" are linked together to form statements directed to their specific needs. For example one of the objects of the document object is bgcolor, the color of the background; this can be set by the following statement:


document.bgcolor = "white";

Likewise, methods can be appended to the objects they control to form statements; document.write applies the write method to the current document . Some objects are also the properties of other objects and are identified by stringing elements together to form an identifier:

document.form[0].address.value refers to the contents of the "address" field on the first form of the HTML document in use. (The connections between objects is best explained in the Navigator Object Hierarchy section of Chapter 3 of the Netscape JavaScript Guide, reference

The JavaScript language syntax is similar to that of Java and based on the constructs of the C and C++ languages, but far looser in structure. Lines of code may be left without any line ending charges (like VBScript) or a semicolon may be added for clarity. Clauses are enclosed within curly braces, like this:


function trustMe {
    statement 1;
    statement 2;
}

Like Unix (but unlike nearly everything else), JavaScript is case sensitive in most cases. Object names like "myObject", "myobject", and "MYOBJECT" are considered different items, resulting in common scripting errors.

Data types and structure

Like many script languages, JavaScript does not use strong data typing. String and numeric data can be mixed and conversions are performed automatically. JavaScript also does not require variables to be defined explicitly, though that practice is recommended. JavaScript's data types include arrays, allowing you to more easily handle groups of items where iterations are likely.

Unlike VBScript, JavaScript does not provide good string manipulation functions until the most recent version (supported only by Communicator 4.0). This version adds string replacement and search functions and Regular Expressions to the language.

Program control, iteration, and selection

Until the most recent version of the interpreter, program control and iteration was largely limited to if statements; now, other structures (do while., case, etc.) are available. The limited support for this level of the interpreter, however, makes it difficult to consider using such capabilities until they are more widely accepted.

Screen interaction

JavaScript provides control over some HTML elements, generating statements according to conditions defined by the application designer. In addition, all of the usual HTML page attributes - such as Title, background color, etc. - are JavaScript objects and can be manipulated as described above.

System information and control functions available

JavaScript is tightly integrated with browser capabilities and can get and set a wide variety of information. System calls allow the language to understand and use the current dimensions of the screen area, user preferences, and many other parameters. Support for these capabilities varies across the range of supported browsers, however, so it is still necessary to carefully consider your needs and the capabilities of your audience.

Development tools

Scripts can be developed with text editors or with many HTML development tools. Netscape provides a script debugger that works in conjunction with their browsers. Microsoft's Script Debugger will also show errors in JavaScript scripts as they occur in their browser, but lacks the context- sensitive help and language documentation features of the Netscape version.

Like most script languages, JavaScript is interpreted at run time; thus, you might have concealed errors that surface only under specific circumstances. This means your customers see error messages or, worse, get no page information at all when they happen to hit those conditions. With any interpreted development environment it's important to test every condition possible to avoid such problems.

Example of Use

A simple form example - similar to the one used with VBScript last month - is shown in Figure 1, below. As with last month's example, the task is to make sure that the user enters a value into a particular field - the username field - and puts up a dialog box on the screen reminding them if they do not. The function to check contents and generate the error message is located at the top of the page, while the action triggering this function is within the onsubmit event descriptor located within the <FORM> tag. In this case, the action specified in the <FORM> tag (sendform.cgi) is not performed until the conditions within validateForm are met.

Note that name of the form is passed as "this" (with the current value "myForm"), but arrives in the function's hands to fill a local variable known as "formName." The value of this field is then expressed as formName.username.value. This example also shows how script code is "hidden" from non- compliant browsers using the SCRIPT tags and open-ended comment lines. To some browsers, the area between these comment areas (e.g. '<!--' and '-->') is ignored. Since the JavaScript interpreter uses a C++-like comment structure (two dashes), it's important to mark your comments carefully.

Conclusion

Like VBScript and other scripting languages for the Web, it's important to understand the needs and capabilities of your audience when designing applications; indeed, all client-side application development faces similar issues. With its larger installed base and broader usage, JavaScript represents a better choice for client-side Web scripting.

Next month: first steps with Perl.

References

There are many good sources of information for JavaScript; the following is just a sample:

JavaScript Guide
http://developer.netscape.com/library/documentation/communicator/jsguide4/

Netscape's definitive guide to JavaScript in its latest versions. The site also has a language reference and many code examples. Of particular note is the "Navigator Object Hierarchy" in Chapter 3 of the Guide, which shows how objects interact in JavaScript.

Getting Started with Netscape Script Debugger
http://developer.netscape.com/library/documentation/jsdebug/index.htm
http://developer.netscape.com/library/documentation/jsdebug/jsd.pdf

Describes the Netscape JavaScript debugger and its use in developing applications. A local copy of the Acrobat version (.pdf) is the best way to use this guide, since invoking the script debugger stops Netscape Communicator from reading other web pages.

Microsoft Scripting Home Page
http://www.microsoft.com/scripting/

Covers all of the Microsoft scripting languages, including JScript (their version of JavaScript) and VBScript. Many free code samples and a script debugging application.

Danny Goodman's JavaScript Pages
http://www.dannyg.com/javascript/index.html

Good collection of information on JavaScript techniques from a long-time scripting wizard.


Figure 1: Sample JavaScript Application


<html>
<head>
<title>Sample Form Using JavaScript</title>

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from old browsers

function isEmpty(str) {
    return (str == null) || (str == "");
}

function validateForm(formName) {
    if(isEmpty(formName.username.value)) {
        alert ("You forgot to enter your name");
        return false;
    }
    return true;
}

// end hide -->
</SCRIPT>

</head>

<body>
<h2>Sample Form Using JavaScript</h2>

<p>Please fill in the items below.
The name field is required for processing.</p>

<form name="myForm" action="sendform.cgi"
 onsubmit="return validateForm(this)">
  <table border="0">
    <tr>
      <td><strong>Name (required)</strong></td>
      <td><input type="text" name="username" size="20"></td>
    </tr>
    <tr>
      <td><strong>Address</strong></td>
      <td><input type="text" name="useraddress" size="20"></td>
    </tr>
    <tr>
      <td><strong>City, State, ZIP</strong></td>
      <td><input type="text" name="usercity" size="20"></td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="submit" value="Submit Entry" name="submitbutton>
        <input type="reset" value="Reset" name="reset">
      </td>
    </tr>
  </table>
</form>
</body>

  [ Prior Article ]     [ Return to the Catalog of articles ]     [ Next Article ]  


Copyright © 1998 Dennis S. Barnes
Reprints of this article are permitted without notification if the source of the information is clearly identified