JavaScript Examples

The second best way to study for the JavaScript exam on October 23rd is to study and understand the two examples I provide (the first is to read the JavaScript tutorial). This first example of using JavaScript is as a <B>wrapper</B> for controlling an application running on a Web page. If the application is written in Java (the language we will study but which is only one example), the application is technically called an <B>applet</B>. The second example I will provide next Tuesday will be a pure JavaScript example that you can study without Java consideration.

As you review example #1 below, you should keep a list of questions you would like to ask in class. I will answer questions on Tuesday and Thursday of next week. You can run the example one code here in your Web browser. Of course your Web browser will have to process JavaScript as most do. Just note that you will get a JavaScript error when you load the page as the Java applet is not active. Do not debug the error. I have placed a temporary image in the place of where the applet would be running. Take a look at the code, read my explanations below, continue reading the JavaScript tutorial, and come back to this link over the weekend for updates.

JavaScript Example #1 -- A Collaboration Wrapper

I have placed numbers in red as discussion reference points in the code below. You can find these reference points by searching on ##. The JavaScript is embedded within the HTML document which is easy to scope by the <HTML></HTML> tag pair. You shouldn't have to understand the HTML to understand the JavaScript, but it certainly doesn't hurt any. After the open <HTML> tag, you see the start of the HEAD element, the TITLE element, and the start of a SCRIPT element. Remember the <SCRIPT></SCRIPT> tag pairs are where the action is for JavaScript. The <SCRIPT> tag should either include a LANGUAGE attribute that specifically identifies the scripting language used or a TYPE attribute that defines the text/javascript MIME type. Either works fine in today's browsers. Look through the file and identify the SCRIPT elements. Look where they are relative to the HTML, HEAD and BODY elements.

## 1 ##

This section identifies variables we want to use within the whole HTML page. If you search on where each variable is used, you will quickly deduce its purpose. If not, we can discuss particular variables in class. As programmers, the name of each variable should identify its purpose as well as possible. Not a perfect job here to say the least. Note that all the variables are identified with the var keyword in front. So, each variable is of variant type and can be used as a number, string, or date. You might consider this lazy programming as we waste computer memory by not being more specific. Such is the way of the JavaScript hacker.

## 2 ##

The Initializing() function runs as soon as the Web page has finished loading. How do you know that? Because the Initializing() function is an attribute value for the BODY element's ONLOAD attribute (see ## 6 ##). In this way, the HTML specification provides us the opportunity to run a single script at load time. But, if you think about it, you only need to call one function as you can then have that function call all the other functions you want to run at load time.

In this example, the Initializing() function is very important. We are controlling a Java applet from within JavaScript. Some of the work we want to do in the Java applet shouldn't start until after the Java applet has finished its loading process. So, we run a loop waiting for the Java to pass a message to the JavaScript saying, "OK. I have finished loading now". This is your first example of calling another technology from within JavaScript. We will need to do that often in this example so be sure to understand how it works.

The JavaScript has access to the Document Object Model (DOM) that is kept by the Web browser upon load (through a parse and store process built into the Web browser). The DOM is standardized by technical specifications in order to be consistent across Web browsers. The statement:

initialized=document.applets.oworld.isInitializing();

calls a function isInitializing() which is a function available in the Java. The Web browser knows the function is in the Java by the fact we've referenced the Java applet through the DOM. How does that work? Reading left to right, the Web browser reads the word document and realizes we are referencing the loading Web page document. Web browser reads the word applets and references all the APPLET elements that have been loaded. The word oworld references the applet with the specific NAME=oworld attribute. The Web browser then calls the isInitializing() function in the right applet. Cool, eh?

All functions have the ability to return a value back to the calling function. Most languages (including Java and JavaScript) have a return keyword in their language that precedes the value to be returned. So, we can imagine, the isInitializing() function returns 0 until it has finished initializing. Then, a 1 is returned. Our JavaScript keeps receiving back 0 until 1 is returned. We assign the returned value to the initialized variable and stop our loop once the 1 is returned. Then, and only then, we know it is safe to call our JavaScript DSUpdate() function.

## 3 ##

The DSUpdate() function runs get information from the Java applet and integrate it with the Javascript. First, you see nine pairs of statements that look like:

appletVer=document.applets.oworld.getVersion();
document.JSForm.appletVersion.value=appletVer;

which uses the DOM again to call the getVersion() function in the applet. The getVersion() function returns the version of the applet as a string. The second line assigns the returned appletVer to the appropriate control within the loaded Web page. Right, the JavaScript again uses the DOM to specify where to display the current version. From left to right, the document refers to the loaded Web page. JSForm refers to the form created by the HTML. The appletVersion is a text box named in an INPUT element (go ahead and search on appletVersion to find it below). The value keyword tells JavaScript to make the version string visible in the text box as its new value.

The other eight statement pairs get information from the Java applet and show the results in INPUT elements. This is a quintessential example of using JavaScript as a wrapper whereby most of the work is being done in another technology yet the scripting language provides a higher level of control. The worldName is the name of the current 3-D environment showing in the applet. The worldFile is the filename of the file that has been loaded in 3-D (a 3-D model file). The numInWorld returns the current number of people on the same page (in the 3-D world).

userName reminds you what your name is since you are representing yourself as that person in the 3-D world. avatarName reminds you which avatar (graphical model) you are using to represent yourself. coordinates tells you where you currently are in 3-D space. heading returns the angle you are facing when considering it from top view. pov returns an index to your point of view (0=first person, 1=behind, 2=above, etc.). These readouts are helpful as you participate in a collaborative discussion through the Java applet.

If you select one of the movement control buttons (see ## 8 ##), you move in the 3-D world. The INPUT controls specify which JavaScript function runs when selected. For example, when you select the ^ button, you wake the forward() function. The forward() function interrogates your current location to make sure you are not too close to the 3-D model bounds (in the case of a rectangular room, we check against a rectangle) and if not, passes your current speed to the Java applet's goForward() function. By now, this should be obvious as you get used to the DOM specification (document.applets.oworld) for the applet. The Java can return the updated position back to the JavaScript for update. The JavaScript update has not been implemented yet to keep this example simpler.

The back function is similar as are the left() and right() functions. But, since the left() and right() functions only turn you and don't change your position, we don't need to check for being within bounds.

## 4 ##

The last thing the DSUpdate() function does is to set a timer that will run the DSUpdate() function again in 1000 milliseconds (1 second). The window.setInterval() is a standard function within the JavaScript language (a very necessary one at that for repetitive event processing). Take a moment and think of all the features such a function provides to Web authors (I've seen it used often for automated kiosk slide shows).

## 5 ##

This series of three scripts determines which version of JavaScript the Web page visitor is using in their Web browser. It shows a couple of interesting things. First, note that the Language attribute is more specific about which version of JavaScript the script is written for. Each script has a single statement (not even within a function which you might again consider lazy). And, all three statements are simple assignments that don't depend on any language feature that isn't in the JavaScript 1.1 specification. Instead, the assignment varies so that only the assignment of the highest JavaScript version that is running in the Web browser is processed. A Web browser will not try to run a script of JavaScript1.3 if it currently only has access to a version 1.2 interpreter.

These three scripts show the flexibility the author has available for choosing how things get done. Oh, by the way, <!-- opens an HTML comment, --> ends an HTML comment, and // means a JavaScript comment follows for the rest of the current line. HTML comments are processed by a Web browser that doesn't understand the scripting language but does understand the SCRIPT element. JavaScript throws away the opening and ending HTML comment symbols, knowing that they are intende for browser that don't understand JavaScript.

## 6 ##

This is just a reminder that your first JavaScript function can run automatically upon load by placing a call to it in the ONLOAD attribute as its value. Remember that we made a function named Initializing() for that purpose (see ## 2 ##).

## 7 ##

The HTML code for adding a Java applet is important to understand as you will be adding your own Java applets to Web pages. For now, the code is commented out (note the HTML comment symbols). HTML provides an APPLET element specifically for Java integration. The APPLET element requires a code attribute to tell the Web browser where the Java program sits in the file system. The width and height attributes tell the Web browser how much room to make for applet visuals. The name attribute is important so the DOM can refer to our applet by name (critical, right, for our JavaScript to be able to communicate with it?).

## 8 ##

These are the movement controls navigation. Note the input elements provide a one to one mapping of HTML visual to JavaScript function. When a function is referenced inside a user interface control, we call that function an event handler since it becomes active only when an event occurs (many common events are activated by the keyboard and mouse).

## 9 ##

Remember that some JavaScript functions act on a Web page in the flow of layout. The document.write() function is the most common. It writes HTML exactly where it is encountered in the body of a document (hence the lack of reference to another HTML element in its DOM usage). The benefit of using JavaScript is you can print out the value of a variable that has been determined elsewhere in your code processing. Think about how these three statements are dependent on their location in the code. Compare that to how the other functions lack the same output immediacy.

THE CODE STARTS HERE:

<html>
<head>
<title>JavaScript Control Example</title>

<SCRIPT Language="Javascript">

## 1 ##
var oTimer="";
var appletVer="N/A";
var worldName="N/A";
var worldFile="N/A";
var numInWorld="0";
var userName="0";
var avatarName="0";
var coordinates="0";
var heading="0";
var pov="0";
var initialized="0";

var x_dim = 100;
var z_dim = 60;
var current_x = 0;
var current_z = 0;

var jsver = "1.0";
var speed = 1;
var collide = 1;
var see_me = 0;

## 2 ##
function Initializing()
{
    while(initialized!="1") {
        initialized=document.applets.oworld.isInitializing();
    }
    DSUpdate();
}
## 3 ##
function DSUpdate()
{   
    appletVer=document.applets.oworld.getVersion();
    document.JSForm.appletVersion.value=appletVer;

    worldName=document.applets.oworld.getWorld();
    document.JSForm.worldName.value=worldName;

    worldFile=document.applets.oworld.getFile();
    document.JSForm.worldFile.value=worldFile;

    numInWorld=document.applets.oworld.getNumInWorld();
    document.JSForm.numInWorld.value=numInWorld;

    userName=document.applets.oworld.getUserName();
    document.JSForm.userName.value=userName;

    avatarName=document.applets.oworld.getUserAvatar();
    document.JSForm.avatarName.value=avatarName;

    coordinates=document.applets.oworld.getCoordinates();
    document.JSForm.coordinates.value=coordinates;

    heading=document.applets.oworld.getHeading();
    document.JSForm.heading.value=heading;

    pov=document.applets.oworld.getPOV();
    document.JSForm.pov.value=pov;
    
    setUpdateTimer();
}
    
<!-- Begin Movement Handlers
function forward() {
    if (current_x<x_dim && current_x>-x_dim && 
       current_z<z_dim && current_z>-z_dim) {
       position = document.applets.oworld.goForward(speed);
       // update current_x and current_z given new position
    }
}
    
function back() {
    if (current_x<x_dim && current_x>-x_dim && 
       current_z<z_dim && current_z>-z_dim) {
       position = document.applets.oworld.goBack(speed);
       // update current_x and current_z given new position
    }
}
function left() {
  document.applets.oworld.turnLeft(speed);
}
function right() {
  document.applets.oworld.turnRight(speed);
}
// End Movement Handlers-->

## 4 ##
function setUpdateTimer() {
    oTimer=window.setInterval(DSUpdate, 1000);
}
</SCRIPT>
</head>
## 5 ##
<SCRIPT LANGUAGE="JavaScript1.1">
    <!-- Begin
    jsver = "1.1";
    // End -->
</SCRIPT>
<SCRIPT Language="JavaScript1.2">
    <!-- Begin
    jsver = "1.2";
    // End -->
</SCRIPT>
<SCRIPT Language="JavaScript1.3">
    <!-- Begin
    jsver = "1.3";
    // End -->
</SCRIPT>
## 6 ##
<body ONLOAD="Initializing()">
<center>
<H2>JavaScript Example #1</H2>
<table>
<tr>
<td>
<IMG SRC=viz.jpg NAME=oworld>
## 7 ##
<!-->
JAVA-BASED VISUALS GO HERE
applet code=com.dspace.client.DsApplet.class ARCHIVE="dspace.zip"
name=oworld width=500 height=520
-->

<!-- Entry Viewpoint -->
<param name="entryViewpoint" value="Team Room">
<param name="entryCoords" value="0,1650,0,0,0">

<!-- Demo Mode -->
<param name="demoMode" value="online-chat">
<!-- /applet -->
<center>
## 8 ##
Movement Controls:
<input type="button" onclick="forward()" value="^">
<input type="button" onclick="back()" value="v">
<input type="button" onclick="left()" value="<">
<input type="button" onclick="right()" value=">">
</center>
</td>
<td>

<!-- Begin HTML Visuals -->
<form name=JSForm>

<script LANGUAGE="JavaScript">
<!-- Begin
## 9 ##
document.write("JavaScript Version: <input type=text name=JScriptVersion value='" + jsver + "'><BR>");
document.write("Browser Version: <input type=text name=browserVersion value='" + this.navigator.appVersion + "'><BR>");
document.write("Launch Page URL: <input type=text name=URL value='" + this.document.URL + "'><BR>");
// end -->
</script>

Applet Version:
<input type=text name=appletVersion>
<br>
Name of World
<input type=text name=worldName>
<br>
File Name of World
<input type=text name=worldFile>
<br>
# Users Logged in
<input type=text name=numInWorld>
<br>
Local User Name
<input type=text name=userName>
<br>
Local User Avatar
<input type=text name=avatarName>
<br>
User Coordinates
<input type=text name=coordinates>
<br>
User Heading
<input type=text name=heading>
<br>
User POV
<input type=text name=pov>
<br>
<hr>
Render
<input type="button" name="Button" value="On">
<input type="button" name="Submit2" value="Off">
<br>
Antialiasing
<input type="button" name="Button2" value="On">
<input type="button" name="Submit22" value="Off">
<br>
Zoom
<input type="button" name="Button3" value="On">
<input type="button" name="Submit23" value="Off">
<br>
Hardware Accl
<input type="button" name="Button4" value="On">
<input type="button" name="Submit24" value="Off">
<br>
Headlight
<input type="button" name="Button5" value="On">
<input type="button" name="Submit25" value="Off">
<br>
Debug
<input type="button" name="Button6" value="On">
<input type="button" name="Submit26" value="Off">
<br>
Test Connection
<input type="button" name="Button62" value="Push Here">

</form>

</td>
</tr>
</table>
</center>
<!-- End HTML Visuals -->
</body>
</html>