|
|||
|
EarthWeb sites: |
Chapter 22Using 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.
Adding Java Applications to Your Web PagesThere 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> TagThis 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">
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.
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"
<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.
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"> This will display the text, instead of the applet, when it encounters a browser that doesn't support Java. The <INSERT> TagAs 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" 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" Example: Adding Java AppletsThis 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> 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). Creating JavaScript ProgramsNow 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> TagThe <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"> Remember that LANGUAGE is optional-you probably won't need to use it while authoring JavaScript, but it can't hurt. Hiding CodeWhile 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> 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> 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 WorldAlthough 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> 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.
FunctionsThe 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 FunctionsA 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> 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> 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 FunctionYou 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; 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; 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 DeclarationsYou 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> 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 EventsWell, 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"> 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.
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"> 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) { 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"> 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) { 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> 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).
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 OneLet'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> 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 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 TwoNow 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> 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.
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. SummaryJava 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
Review Exercises
|
Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details. |