Chapter 22

Using Java and JavaScript


CONTENTS


We should start this chapter by making a distinction between Java and JavaScript. Java is an object-oriented, compiled (at runtime), full-fledged programming language in the spirit of C++. It is designed for the more advanced programmer, with its strength being the ability to run in a "virtual machine" that can be created by a Web browser. Java, then, is similar to the programming languages used to build full-fledged applications that can be run on PCs, Macs, and UNIX machines. It's well-suited for the Internet, but not necessarily exclusive to the Web.

JavaScript, on the other hand, is a less complex, interpreted scripting language similar to AppleScript, Visual Basic Scripting, and similar languages. JavaScript is similar in some ways to Java, but it doesn't require the programmer to understand or implement the complicated object-oriented syntax or worry about programming issues like variable typing and object hierarchies.

In fact, Java and JavaScript are different enough that you can think of them with different titles depending on your ability. It's convenient to think of creating programs in Java as programming, and you can call creating scripts in JavaScript authoring.

Note
Java programming is outside of the scope of this book. (I'd suggest Java by Example or Special Edition Using Java from Que.) In this chapter, you'll learn about adding Java programs to your HTML pages, and then look at the basics of JavaScript authoring.

Adding Java Applications to Your Web Pages

There are two basic ways to add Java applets (programs) to your Web pages. The first is an HTML-like extension that Netscape and other companies rolled into their browsers as the Java language first became popular. For a while, at least, this will be the preferred way of adding applets. The other method, based on the HTML 3.0 suggested <INSERT> tag, is still under discussion at the time of writing but should eventually replace the more proprietary <APPLET> tag.

The <APPLET> Tag

This first method adds the HTML-like tag <APPLET> container tag. Along with the <APPLET> tag is the <PARAM> tag, used to offer certain parameters to the browser concerning the applet (like the speed at which something should display, initialize, and so on). <APPLET> accepts the attributes CODE, CODEBASE, HEIGHT, and WIDTH.

An <APPLET> tag follows the general format:

<APPLET CODEBASE="applet_path_URL" CODE="appletFile.class" WIDTH="number" HEIGHT="number">
<PARAM NAME="attributeName" VALUE="string/number">
...
Alt HTML text for non-Java browsers
</APPLET>

CODEBASE is the path (in URL form) to the directory on your server containing the Java applet. CODE takes the name of the applet. This file always ends in .class, to suggest that it's a compiled Java class. CODE should always be just the filename since CODEBASE is used to find the path to the Java applet.

Tip
Notice that CODEBASE and CODE work together to create a complete URL. So, for a relative URL, CODEBASE isn't required if the applet is in the same directory as the Web page.

The WIDTH and HEIGHT attributes accept the number in pixels for the Java applet on your Web page.

An example of the first line of <APPLET> would be the following:

<APPLET CODEBASE="http://www.fakecorp.com/applets/" CODE="clock.class"
HEIGHT="300" WIDTH="300">

<PARAM> is a bit easier to use than it may seem. It essentially creates a variable, assigns a value, and passes it to the Java applet. The applet must be written to understand the parameter's name and value. NAME is used to create the parameter's name; it should be expected by the applet. VALUE is used to assign the value to that particular parameter. It could be a number, bit of text, or even a command that causes the applet to work in a particular way.

Note
Understanding the <PARAM> tag might enable you to use freeware/shareware Java applets on your own pages. By passing your own parameters to general purpose applets, you may find them useful for your particular Web site.

A simple <PARAM> tag is the following:

<PARAM NAME="Speed" VALUE="5">

In this case, the Java applet will have to recognize and know what to do with a variable named Speed with a value of 5.

The alternative HTML code in the <APPLET> container allows you to offer HTML text to browsers that aren't Java-enabled. A Java-aware browser will ignore the markup (and display the applet window instead), while non-Java browsers will ignore everything but the markup. So an example would be the following:

<APPLET CODE="counter.class" HEIGHT="20" WIDTH="20">
<P>You need a <I>Java-aware</I> browser to see this counter!</P>
</APPLET>

This will display the text, instead of the applet, when it encounters a browser that doesn't support Java.

The <INSERT> Tag

As you may remember from Chapter 16, the <INSERT> tag is the current thinking by the W3C for adding inline multimedia elements to Web pages. In fact, it's designed to work for Java applets as well, as most browsers work with applets in a way similar to inline video and animations.

The basic format for the <INSERT> tag (as it regards Java applets) is as follows:

<INSERT CLASSID="Java:filename.class"
        CODE="URL/filename.class"
        WIDTH="number"
        HEIGHT="number"
        ALIGN="direction">
<PARAM NAME="name" VALUE="number/string">
<IMG SRC="URL" ALT="text">
</INSERT>

For the most part, this works a lot like the <APPLET> tag, except that it does away with the CODEBASE tag, instead requiring that you use a full URL for the CODE attribute. (This makes more sense in terms of the HTML conventions you've learned in the past.) The CLASSID is a MIME type name, which is required for all <INSERT> tags. HEIGHT and WIDTH are just numbers that represent pixels for the applet window on your Web page. ALIGN works as it does for other <INSERT> elements.

The <PARAM> tag for <INSERT> elements is essentially the same as the <PARAM> tag you used previously for the <APPLET> tag. Your Java applet will still need to recognize and deal with the incoming data. The <IMG> tag, as with other <INSERT> elements, allows you to add the URL to an image that can display in browsers that aren't Java-enabled.

An example might be:

<INSERT CLASSID="Java:counter.class"
        CODE="http://www.fakecorp.com/applets/counter.class"
        WIDTH="20"
        HEIGHT="20"
        ALIGN="LEFT">
<PARAM NAME="Speed" VALUE="5">
<IMG SRC="nojava.gif" ALT="This applet requires a Java-enabled browser">
</INSERT>

Example: Adding Java Applets

This example is designed to do two things: reinforce the ways you can add Java applets to your Web pages, and test your browser for Java capabilities. If your browser supports Java, it'll be interesting to see which method it prefers for adding Java applets.

To begin, create a new HTML page and add the code in Listing 22.1.


Listing 22.1  addjava.html  Adding Java Applets to a Web Page
<BODY>
<H3>This applet has been added using the APPLET tag:</H3>
<APPLET CODE="Clock2.class" HEIGHT="150" WIDTH="150">
{<P>You need a <I>Java-aware</I> browser to see this clock!</P>}
</APPLET>
<HR>
<H3>This applet was added using the <INSERT> tag:</H3>
<INSERT CLASSID="Java:Clock2.class"
        CODE="Clock2.class"
        WIDTH="150"
        HEIGHT="150"
        ALIGN="LEFT">
<IMG SRC="no_work.gif" ALT="Looks like Insert doesn't work!">
</INSERT>
</BODY>

Save this file as clock.html. To get this to work correctly, you'll need a Java applet. You can use an applet written by Rachel Gollub of Sun Microsystems, clock2.class which is available on the included CD-ROM. Make sure it's in the same directory as clock.html. Then load the page in your browser to test it (see fig. 22.1).

Figure 22.1 : Here's what works and what doesn't in my copy of Netscape Navigator (Mac 2.0 Java beta).

Creating JavaScript Programs

Now let's move on to JavaScript, the smaller Java-like scripting language available in Netscape Navigator and other programs. Unlike Java, JavaScript programs are generally written right in HTML pages. You'll start with how to add JavaScript code to a Web page and then look at how these programs are created.

The <SCRIPT> Tag

The <SCRIPT> tag is used to add JavaScript commands to your HTML pages. <SCRIPT> is a container tag that can accept the attribute LANGUAGE, which allows you to specify the scripting language used (JavaScript is generally the default). Here's how it works:

<SCRIPT LANGUAGE="lang_name">
script code
</SCRIPT>

Remember that LANGUAGE is optional-you probably won't need to use it while authoring JavaScript, but it can't hurt.

Hiding Code

While it's possible that old browsers (those that don't recognize JavaScript) will just skip over the <SCRIPT> tag, it's also possible that the browser will attempt to interpret your script commands or other text as HTML markup. To keep this from happening, you can embed the script commands in HTML comments. You might try something using the HTML comment tags like the following:

<SCRIPT>
<!--
script commands
-->
</SCRIPT>

This works fine for the non-Java browser. Unfortunately, the JavaScript will choke when it sees -->, since it will try to interpret that as scripting code. So you need to comment the comment.

In fact, it's always a good idea to create comments within your script that allow you to document what you're doing in your programming. Unfortunately, you've just told Java-enabled browsers that HTML comments (between <SCRIPT> tags) contain active script commands. So how can you add comments for the benefit of the script? Like this:

<SCRIPT>
<!--
script command    // One-line comment
...script commands...
/* Unlimited-length comments must be
ended with
*/
// comment to end hiding -->
</SCRIPT>

Looks like you can fill a decent-sized page with nothing but comments, eh? Notice that you've solved the HTML comment problem with a single-line JavaScript comment. Single-line comments start with two forward slashes and must physically fit on a single line with a return at the end. Multi-line comments can be enclosed in between an opening comment element (/*) and a closing comment element (*/).

Example: Hello World

Although you haven't learned how to do anything with a script yet, I'll throw one quick command at you for the purpose of getting your first JavaScript page to work. It's document.write, and it's something called a method in JavaScript. It's basically a variable that does something automatically. In this case, it prints text to your Web page.

Create a new HTML document and enter Listing 22.2.


Listing 22.2  hiworld.html  "Hello World" JavaScript Document
<HTML>
<HEAD>
<TITLE>Hello World JavaScript Example</TITLE>
</HEAD>
<BODY>
<H3>The following text is script generated:</H3>
<SCRIPT LANGUAGE="JavaScript">
<!--
/* Our script only requires
one quick statement! */
document.write("Hello World!") // Prints words to Web document
// end hiding-->
</SCRIPT>
</BODY>
</HTML>

Save this document, and then load it in the browser of your choice. If your browser is capable of dealing with JavaScript, then your output should look something like figure 22.2. If it's not, then you'll just see the header text.

Figure 22.2 : Your first JavaScript program.

Tip
If your browser can't see the JavaScript example, I suggest getting the latest copy of Netscape Navigator for testing your work in this chapter.

Functions

The basic building block of a script in JavaScript is the function. A function is basically a "mini-program." Functions start by being "passed" a particular value; they work with that value to make something else happen and then "return" a new value to the body of your program.

In JavaScript, there are two times you need to work with functions. First, you need to declare the function. This means that you're defining how the function will work. The browser, when it loads a page, will make note of the different functions that you may use in your script.

The second step is to call the function in the body of your script. Generally, your script will be just a series of function calls. There isn't a whole lot of calculating done in the body of your script. You send a value out to a function to be computed and then receive the results back in the body of your script.

Declaring Your Functions

A good rule, although it's not necessary, is to declare your functions in the head of your document. The function declaration needs to appear between <SCRIPT> tags, but you can have more than one set of <SCRIPT> tags in an HTML document. A single set of <SCRIPT> tags doesn't necessarily define an entire script-it just sets script elements apart from other HTML tags. Function declarations look like the following:

<SCRIPT>
<!--
  function function_name(value_name) {
  ...function code...
  
return (new_value)
}
// end hiding -->
</SCRIPT>

The value_name for the function is just the variable name that you assign to the passed value for the duration of the function. When the body of your JavaScript document calls this function, it will generally send along a value. When that value gets to the function, it needs a name. If the function is designed to perform simple math, for instance, you might call the passed value old_num.

Also, notice that the entire calculating part of the function is between braces. An example of a function declaration might be the following:

<SCRIPT>
<!--
  function get_square(old_num) {
  new_num = (old_num * old_num)
  return (new_num)
}
// end hiding -->
</SCRIPT>

In the example, you've created a function called get_square which accepts a value, names it old_num, and then squares that value and assigns it to a variable named new_num. At least, that's what the function is supposed to do. It won't do it yet, because this is just a declaration. It doesn't even know what actual values to work with until you call the function.

Calling a Function

You call the function from the body of your script, which is generally in the body of the document. It doesn't really matter where you declare functions (although, as mentioned, it's best to declare them between the <HEAD> tags), but it is best to put the function calls of your script close to the parts of your document where they're needed (this will become more obvious as you work with JavaScript). A function call is basically formatted like the following (and always appears between <SCRIPT> tags):

function_name(value);

In this function call, the function_name should be the same function name that you used in the function declaration, while the value can be anything you want to pass to the function. In the previous example, this value was to be renamed old_num and then squared. So it would make sense to put a number in the parentheses of that particular function call. In fact, you can put almost anything in the parentheses-a variable name, an actual number, or a string of text-as long as the function is designed to accept such a value. For instance, the get_square function will work equally well if you use:

number = 5;
num_squared = get_square (number);

or

num_squared = get_square (5);

By the way, if something looks strange to you here, it might be the way I'm naming variable names-especially if the last time you did any programming was a number of years ago. The following would work just as easily:

x = 5;
y = get_square (x);

Does that make you more comfortable?

Remember, though, that you should be passing a value that the function expects. If you pass a string of text to a function designed to perform math functions, you won't get anything useful.

Notice also that, in the previous three examples, the function is on the right side of an assignment, represented by the equal sign. This may take a little leap of thought, but JavaScript does two things with function calls. First, the call is used to pass a value to the function. Then, when the function returns a value, it "takes the place" of the original function call.

Look at the following example:

num_squared = get_square (5);

After the math of the get_square function is completed and the value is returned, the entire function call (get_square (5)) is given a value of 25. This, in turn, is assigned to the variable num_squared.

Example: Calling All Declarations

You know enough now to build a fairly simply little script. You'll use document.write again, with a function declaration and a function call. In this script, you'll do some simple math and track the results in your browser window.

Create a new HTML document and enter Listing 22.3.


Listing 22.3  simpmath.html  Using JavaScript for Simple Math
<HTML>
<HEAD>
<TITLE>Simple Math</TITLE>
<SCRIPT>
<!--
  function simple_math(num) {
  document.write("The call passed ",num," to the function.<BR>");
  new_num = num * 2;        // multiple the value by 2
  document.write(num, " * 2 equals ",new_num,"<BR>");
  return new_num;           // return new_num to the function call
}
// end hiding -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Let's watch some simple math:</H3>
<SCRIPT>
<!--
  x = 5;
  document.write("The starting number is ",x,"<BR>");
  new_x = simple_math(x);
  document.write("The function returned the number ",new_x,"<BR>");
// end hiding -->
</SCRIPT>
</BODY>
</HTML>

And that's pretty much it. Notice that document.write lets you track the progress of your number as it moves from the function call through the function itself and back down to the main part of your script. You can see this working by focusing on the order of the output in figure 22.3.

Figure 22.3 : The results of your script.

Handling Events

Well, you've created a complete script, but it can't do much. That's because the strength of JavaScript, more than anything else, is in event handling. That is, it's best at responding to something a user does on your page. This is generally done in response to some HTML tag. Here's the basic format for an event handler:

<TAG event_handler="JavaScript code">

<TAG> can be just about any form or hyperlink tag. Most other tags don't have the ability to accept input from the user. The event_handler is the browser's code for some action by the user. The JavaScript code will most often be a function call.

For instance, you could use an input textbox to send data to a function you've written, as with the following code:

<INPUT TYPE="text" NAME="number" SIZE="4">
<INPUT TYPE="button" NAME="Calculate" onClick="result =
compute(this.form.number.value)">

In this example, you're responding to the event created when the user clicks the input button. When that happens, the value this.form.number.value is sent to a function called compute. Notice that the variable this.form.number.value is JavaScript's object-oriented way of storing the value of the textbox named number in the first statement.

Returning Values

Let's dig a little deeper into how the object-oriented storage thing works. Your average object is usually just a bunch of grouped variables. For instance, a typical browser has a JavaScript object called this, which (in our example) means "variables for this page." Within this is a subcategory called form which means "the form variables." So the name this.form is basically where "the form variables for this page" are stored.

Note
Actually, this is a special keyword in JavaScript, used to refer to the current object. In the case of our example, the current object is, in fact, where the "variables for the page" are stored. We'll discuss the correct use of this a bit more in Chapter 23, "JavaScript Objects and Functions."

When you use the NAME attribute to an <INPUT> tag, you're creating another variable within this object. For instance, NAME="mynumber" creates this.form.mynumber. The value of this variable is stored at this.form.mynumber.value.

Let's look at that last example again:

<INPUT TYPE="text" NAME="number" SIZE="4">
<INPUT TYPE="button" NAME="Calculate" onClick="result =
compute(this.form.number.value)">

Now, the neat trick here is that you don't necessarily have to pass the specific value to a function in order to use it. All you need to do is send the name of the object that you want the function to concentrate on. That way, it can deal with more than one value from that object.

Consider this. You've just gathered this.form.number.value from the textbox. Now you want to send that to a function. You can make the function call like this:

<INPUT TYPE="button" NAME="Calculate" onClick="result = compute(this.form)">

You've also cleverly designed the function to work with this value. So your function will look something like the following:

function compute(form) {
  new_number = form.number.value;
  new_number = new_number * 2;
  return (new_number);
}

The function received what's known as a pointer to the object responsible for storing information about this page. Once the function has its hands on that pointer (which the function calls form), it's able to access data within that function by using the object variable scheme, as in form.number.value. Get it?

But this gets even cooler. If the function knows the pointer to the data storage object, then it can also create new variables within that object. So you can change a few more things:

<INPUT TYPE="text" NAME="number" SIZE="4">
<INPUT TYPE="button" NAME="Calculate" Value="Click Me"
onClick="compute(this.form)">
<INPUT TYPE="text" NAME="result" SIZE="8">

Now (in the second line), you're just telling the browser to run the compute() function when the Calculate button is clicked. But you're not assigning the function to a value. So how do you get an answer for your user? By using the object pointer. Here's the new function:

function compute(form) {
  new_number = form.number.value;
  form.result.value = new_number * 2;
  return;
}

In line three of the function declaration, notice the new variable form.result.value. What happens now is the function call sets the function in motion and passes it the object pointer. The function creates its own new variable within the object, called result, and gives it a new value. When the function returns, the next line of script is activated. That line is:

<INPUT TYPE="text" NAME="result" SIZE="8">

Notice the NAME. Since there's already a value assigned to this NAME, that value will be displayed in the textbox (just as if it were default text). In your case, it happens to be the answer (see fig. 22.4). Here's the complete code again:

Figure 22.4 : Your textbox script, complete with a result.

<HTML>
<HEAD>
<TITLE>Compute A Number</TITLE>
<SCRIPT>
<!--
function compute(form) {
  new_number = form.number.value;
  form.result.value = new_number * 2;
  return;
}
// -->
</HEAD>
<BODY>
<INPUT TYPE="text" NAME="number" SIZE="4">
<INPUT TYPE="button" NAME="Calculate" Value="Click Me"
onClick="compute(this.form)">
<INPUT TYPE="text" NAME="result" SIZE="8">
</BODY>
</HTML>

Possible Events

There are a number of different events that a typical browser will recognize, and for which you can write handlers. Even the simplest handler should call a function you've declared previously and then elegantly return to that point in the Web document. Table 22.1 shows you some of the events for which there are associated handlers (according the Netscape Navigator's documentation).

Table 22.1  Events and Their Event Handlers

EventMeans… Event Handler
blurUser moves input focus from form box onBlur
clickUser clicks form element or link onClick
changeUser changes a form value onChange
focusUser gives a form box input focus onFocus
loadUser loads the page in the Navigator onLoad
mouseoverUser moves mouse over a link onMouseOver
selectUser selects form input field onSelect
submitUser submits a form onSubmit
unloadUser exits the page onUnload

You can probably figure out what most of these do from the table. And it should also make you realize how scriptable your Web page really is. You can create alert dialog boxes, for instance, that tell your user that a particular field is required-or that it needs to be filled with a certain number of characters. You can even say "Goodbye" to users as they leave your page, perhaps displaying a phone number of other useful (albeit intrusive) information.

Example: Event Handling, Part One

Let's start with the simple event I just mentioned-creating an alert to say goodbye. As an added bonus, you'll learn how to create an alert box, which is simply a dialog box that requires your user to click OK to clear the box.

You may want to use an HTML document you've created previously. Any document will do. Add Listing 22.4 to the head and body of your page.


Listing 22.4  events1.html  Handling a Simple Event
<HTML>
<HEAD>
<TITLE>Saying Goodbye</TITLE>
<SCRIPT>
<!--
  function goodbye () {
  alert("For more information about BigCorp products\nPlease call
  1-800-BIG-CORP");
  return;
  }
// end hiding -->
</SCRIPT>
</HEAD>
<BODY>
<A HREF="http://www.netscape.com/" onClick="goodbye()">Click here to leave.</A>
</BODY>
</HTML>

I've re-introduced something else too (you originally saw it with form processing and CGI scripts in Chapter 14). It's the newline character \n which allows you to add a newline in the middle of a text string that's to be written to the browser or another interface element.

It is possible to have eliminated the function goodbye with a simple line of script like the following:

onUnload="alert('For more information about BigCorp products\nPlease call
1-800-BIG-CORP')"

Notice that this forces you to use the single quote character for the alert text. If you prefer to script this way, that's okay. But realize that it's generally considered poor programming technique since it includes actual calculations in the interior of your HTML code. For best results, you want to separate the calculations into functions, which should all be stored in the head of your document. Either way, it should look something like figure 22.5.

Figure 22.5 : Before the current link is followed, this alert will appear.

Example: Event Handling, Part Two

Now letxs use event handling for something a little more complex and perhaps more useful. One of the best uses of event handling seems to be for verifying form data. You can use JavaScript to hand off your data object pointer to a function, which can then take a close look at what your user has entered and determine if it's correct.

We'll try it for a ZIP code. You're simply going to make sure that the user has entered five numbers. Enter Listing 22.5 in a new HTML document.


Listing 22.5  events2.html  Verifying Form Data with JavaScript
<HTML>
<HEAD>
<TITLE>Data Checking</TITLE>
<SCRIPT>
<!--
  function zip_check (form) {
  zip_str = form.Zip.value;
  if (zip_str == "") {
     alert("Please enter a five digit number for your Zip code");
     return;
     }
  if (zip_str.length != 5) {
     alert ("Your Zip code entry should be 5 digits");
     return;
     }
  return;
  }
// end hiding -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Please fill out the following form:</H3>
<FORM ACTION="http://www.fakecorp.com/cgi-bin/address_form">
<PRE>
Name:    <INPUT TYPE="TEXT" SIZE="50" NAME="Name">
Address: <INPUT TYPE="TEXT" SIZE="60" NAME="Address">
City:    <INPUT TYPE="TEXT" SIZE="30" NAME="City">
State:   <INPUT TYPE="TEXT" SIZE="2" NAME="State">
Zip:     <INPUT TYPE="TEXT" SIZE="5" NAME="Zip"
          onChange = "zip_check(this.form)">
Email:   <INPUT TYPE="TEXT" SIZE="40" Name="Email">
<INPUT TYPE="SUBMIT" VALUE="Send it" onClick = "zip_check(this.form)">
</FORM>
</BODY>
</HTML>

This event handling script checks an entry in the Zip box, using the onChange handler to determine when the user has moved on from Zip's textbox (either by pressing Tab or clicking in another textbox with the mouse). Notice that it's a good idea to place the Zip textbox before the E-mail box since the user could just click the Submit button and skip past your error check.

Also, by adding the onClick event to the Submit button, you're able to catch them if they happen to skip the Zip box completely. Now you've double-checked their entry.

I've also cheated and introduced another new method. In the function declarations, you may have noticed the following line:

if (zip_str.length != 5) {

variable.length is a method that allows you to determine the length of any variable in JavaScript. Since JavaScript does no variable typing (it doesn't explicitly require you to say "this is a number" or "this is text"), then any variable can be treated as a string. In this case, even though the ZIP code could be interpreted as a number, zip_str.length tells you how many characters long it is.

The above snippet could be said "if the length of zip_str does not equal 5, then…." Notice that != is the "does not equal" comparison. Similarly, == is the "does equal" comparison. Look at the following snippet from the braces function declaration:

if (zip_str == "") {

This could be read as "if zip_str equals nothing, then…." If the condition (zip_str == "") is true, then the code specified by the braces is performed.

Tip
Be very careful that you use == for comparisons and = for assignments. If you've accidentally used (zip_str = ""), that means "make zip_str equal nothing." You've made it so that the condition is always true since it's an assignment.

You'll learn more about conditions and JavaScript methods in the next chapter. For now, let's just see this script in action, in figure 22.6.

Figure 22.6 : Error checking with JavaScript.

Summary

Java and JavaScript are distinct entities-Java being a sophisticated full-fledged programming language while JavaScript is a smaller, easier-to-grasp scripting language.

There are two ways to add Java applets to your Web pages. The first, using the <APPLET> tag, is currently more pervasive. The second is the <INSERT> tag, HTML 3.0's all-purpose tag for adding multimedia and applet files to HTML documents.

JavaScript can be added directly to your HTML pages, fitting between <SCRIPT> tags. Script code should be hidden between HTML comment tags, to keep it from being interpreted by non-JavaScript browsers.

There are two basic parts to any JavaScript script: the function definitions and the function calls. Function definitions should be in the head of your HTML document, while function calls can appear anywhere you want in the <BODY> of your document. Function calls can also appear as event handlers in certain HTML tags. One of the strengths of JavaScript is error checking for HTML forms.

Getting serious about JavaScript authoring requires an understanding of the object-oriented methods used to store variables related to your page. You can then pass pointers to these data objects to your functions, which allow you to work with more than one variable at once, creating scripts that accomplish more.

Review Questions

  1. Which of the tags, <APPLET> or <INSERT>, is the Netscape-specific way to add Java applets?
  2. Can Java applets be stored in the same directory as your HTML pages?
  3. What is the <PARAM> tag used for with <APPLET> and <INSERT>?
  4. What attribute can the <SCRIPT> tag accept?
  5. What do you call the type of JavaScript command that document.write represents?
  6. In the following function declaration, where does the value for number come from?

    function add_two (number) {
  7. What's wrong with the following script?

    <SCRIPT LANGUAGE="JavaScript">
    <!--
    document.write("Hi!")
    -->
    </SCRIPT>
  8. What is the purpose of an event handler? What's an event?
  9. True or false. If a function call sends the value this.form, then the function declaration must call the value form, as in calculate (form).
  10. What is the full object-hierarchy style name for the value created by <INPUT NAME="city">?
  11. Why is a blur event called a blur event?
  12. What method can be used to determine the length of a variable string?

Review Exercises

  1. Write a JavaScript script (and the HTML page) that asks for the user's name and then tells the user how many characters are in his/her name.
  2. Write a script and page that shows an alert box when the user clicks an anchor link.
  3. Now, write a script that pops up an alert when the user clicks the link, but doesn't move him or her to a new HTML document or part of an HTML document. (For instance, clicking the word hypertext brings up an alert with the definition of hypertext.)
  4. Write a script that pops up an alert when the user touches a graphic with the mouse pointer. (Hint: make it a clickable graphic. Suggestion: use a picture of a person and make the alert say "Stop touching me, I'm ticklish," or something similar.)
  5. Write a script that determines whether or not a number entered in a textbox is "798."