AIA Workshops
Guide to JavaScript
Adding JavaScript to Web Pages.
Please send additions, corrections & suggestions.
Contents --> What is JavaScript? - JavaScript basics through examples - Sample JavaScript quiz


WHAT IS JAVASCRIPT?

Perhaps it's easiest to start by explaining what JavaScript isn't. It is not a new kind of CGI (Common Gateway Interface), the traditional way of processing fill-in forms on the Web. With CGI, interactivity involves the Web server, since the user input from the form is sent back to the server, where it is processed, and then some kind of response is returned to the user. JavaScript (among other things) also can process forms, but it does so locally, on the user's machine, without contacting the server. The Web server's role with JavaScript is limited to serving the Web page containing JavaScript to the user. Since server access is not required, the HTML files containing JavaScript could just as easily be called up locally from the hard drive or a floppy disk. This makes the use of JavaScript more flexible than CGI, since it can be used on computers which are not even connected to the Internet.

JavaScript is not the same as Java. Java is a full-fledged programming language allowing for creation of "applets" or mini-programs which can be run inside of Web browsers such as Netscape Navigator. Although applets appear to be integrated into the Web page displayed, they are actually independent programs and in fact Java can be used to create programs divorced from Web pages. Java applets are not part of the HTML which displays the page, although some parameters of Java applets may be set through the use of HTML. Java must be compiled (translated into computer code) before running. JavaScript on the other hand functions as an add-on to HTML and appears as text alongside familiar HTML codes; JavaScript code is interpreted and run by the Web browser when a user retrieves the Web page, it does not need to be compiled into a program.

The fact that Java applets are compiled means that if you want to take a peek at the code to see how that clever person created that special effect -- you're out of luck. The only way you can see the underlying code is if the programmer decides to make it available to you in text form. Since JavaScript is text and is included alongside regular HTML, you can see its code. Simply "view document source" on your Web browser and you'll see not only the HTML but the JavaScript as well. This makes it much easier to learn, since you can see and borrow code in just the same way you can with HTML. Probably the best way to get started is to take some existing JavaScript code and to paste it into one of your own Web pages. After you get it to work with your page, you can go in and customize the code to fit your needs. Be forewarned -- as you'll see in the next section, JavaScript is computer code and despite Netscape's contention that it derives from (reasonably comprehensible) scripting languages such as Hypertalk (HyperCard's language), it definitely is geektalk and any similarity it has to English is just a passing coincidence. I might mention that if you do take the plunge and learn JavaScript, you'll be half way home to learning Java. The syntax is virtually identical, Java simply adds much more to the language which increases dramatically its functionality.

To top of page JAVASCRIPT BASICS THROUGH EXAMPLES

If you've been surfing the Web much, you will have encountered sites using JavaScript, most commonly in the form of a running message in the status bar at the bottom of the browser window or through an "alert" window that pop ups when you first access the page. There are any number of cute but ultimately annoying "features" you can add to Web pages using JavaScript. We have to accept the interactive functionality that JavaScript and other innovations bring at the cost of having to endure vapid rolling messages or frantically repeating animations. The frequency with which we encounter the running message in the status bar, by the way, is an indication of how easy it is to copy and paste JavaScript into your pages, since that code is quite complex, whereas finding the string to change inside that code from "Welcome to Netscape" to "Welcome to Bob's page of aggravating gimmicks" is no sweat.

1) Displaying alert boxes

Speaking of annoying gadgets, let's look first at how to create a pop-up alert window. Actually, this function can be useful. Say you want to inform your students of an important change in the class schedule -- you could make your point very clearly with such a pop-up alert. Clicking on the link in the previous sentence produces the alert message (assuming you're using a Web browser with JavaScript capability) but that could also happen automatically when the page is laoded. We're look at that option first.

There are actually two snippets of JavaScript that causes this alert to pop up when the page is loaded. This is how the HTML at the top of the page looks:

<html>
<head><title>JavaScript Mini-Tour</title>
<! -- Hide JavaScript from non-compatible browsers>
<script language = Javascript>
function showAlert () {
   alert ('Welcome to JavaScript!')
}
</script>
<!-- end hiding -->
You will normally define in this way between <script> tags the JavaScript "functions" (or sub-routines) which you want to have available to the user at the opening of your HTML file. Note that if you don't want users without a JavaScript-capable browser to see the JavaScript code on their screen, you can use the commenting tags in HTML "<! -->" to hide the code. The "function showAlert()" line begins the definition of the function I've named "showAlert." This is a function I am defining so I could have given it any name such as "PeanutsAndBeer", but it helps to use a name that has some relationship to what the function does. Capitalization is up to you, but JavaScript is case sensitive so you'll need to write the name of the function exactly the same way later on. The line "alert ('Welcome to JavaScript!')" defines between curly brackets the action we want to have take place when the function "showAlert()" is evoked later. In this case we're using a predefined function called "alert()" which displays an alert window. Now all we have to do is to activate the "showAlert()" function, in this case by telling the browser to run the function when the page is loaded. We do that with the following JavaScript at the end of the HTML file:

<script>
onLoad = showAlert()
</script>
</body>
</html>
Once again "onLoad" is predefined and tells the browser that whatever follows the equal sign should be done when the user loads the page, in this case run the "showAlert()" function.

We called our "showAlert()" function from an "onLoad" script, but that function (and any other) can be evoked in a number of ways. We could, for example, create a hypertext link which would also result in the alert window being displayed:

<A HREF = "javascript: showAlert()">Pop up alert window</a>
This is the familiar syntax for defining a hypertext link, but in this case "http://" is replaced with "javascript:". Another possibility is to create a button to perform that action:

In this case, the code to create the button must be placed within "form" tags since a button is a form element (as are text entry fields, radio buttons and checkboxes) and won't be displayed unless within a defined form. The code for doing that looks like this:

<form>
<INPUT TYPE = button VALUE = 'Pop up alert' onClick = alert ('Hello world!')>
</form>
In addtion to the alert window, there are several other dialog boxes which can be accessed through Javascript, which can ask the user to make a choice or to write in some text.

2) Putting text in status bar

I mentioned earlier using JavaScript to place a message in the status bar. Here's an example of causing a message to appear when the user puts the mouse cursor over a specific hypertext link. The JavaScript for this is put into the hypertext link:

<A HREF = "anylink.html" onMouseOver = "window.status = 'Here I am, down here!';return true">Pass mouse over me</a>
Once again, "onMouseOver" is pre-defined in JavaScript. One use of this function is to create a glossary, which is activated by the cursor moving over a phrase.

3) Opening and writing to windows

One of the most useful functions in JavaScript is the ability to open new windows and write to them. We are using here a "javascript:" link to call the function "openWindow()" which we had defined in the header:

function openWindow () {
    window.open("hello.html","hello","width=240,height=200");
}
Note that we can specify the size of the new window, as well as other features, such as whether it displays the tool bar, is scrollable, etc.
 

We can also write to the window we've created. This can also be done to a frame. To see this in action, we will need to first this document with frames.

When we click on "Write to top frame," the "writetoFrame1()" function is executed, putting "Hello world" into the top frame. The code for this function looks like this:

function writeToFrame1 () {
    parent.frames[0].document.clear();
    parent.frames[0].document.open();
    parent.frames[0].document.write('<HTML><BODY BGCOLOR=white>');
    parent.frames[0].document.write('<CENTER><H2>Hello world!');
}

The first line defining the action of the function is a good example of the object-oriented nature of JavaScript:

"parent.frames[0].document.clear();"
Starting from the right side, we first have the pre-defined "clear()" which empties the window in preparation for writing. What is it we want to clear? The "document." Which document? The one in the frame. Which frame? "Frames[0]". Huh? The top-most frame as defined in the "parent" document -- "jstour.htm" which contains the code defining two frames. The frames, as are other objects like links, form fields, or images are thought of as being members of an "array" or list. JavaScript starts counting with "0", so the first frame in "frames[0]", the first image on the page is "images[0]", the second image is "images[1]."

In the previous function, we cleared the top frame, opened it, wrote to it but did not "close()" it -- that means we can keep writing to it:

function writeToFrame2 () {
    parent.frames[0].document.write('Hello again!<H2><CENTER>');
}
Note that the text continues to be centered, since the opening "<CENTER>" tag from the first function is still in effect. The frame is not reloaded when the additional text is written, it's simply added on. This allows you to display a Web page incrementally, allowing, for example, for a demonstration of how a complex sentence is constructed word by word.

4) Manipulating values in form fields

Another very useful JavaScript feature is its ability to manipulate data in forms. The next example shows that you can create customized buttons as well as write to fields in a form.

This field to be filled in with a value by JavaScript:

Clicking on the first button puts the string "Hello world!" into the field. Clicking the second button selects that field. The code:

<input type=text name=field1>

<input type=button value="Put in value" onClick="document.forms[3].field1.value='Hello world!'">

<input type=button value="Select value" onClick="document.forms[3].field1.focus();document.forms[3].field1.select()">

Note that the first "input" tag defines the fill-in form and names it "field1", defining it as a "text field." The reference in the buttons through "document.forms[3].field1.value" is in the normal dot syntax to this field. This functionality is used in the quiz example described in the next section.

Since JavaScript can access the contents of a field, it can also determine if what the user typed into the form is a correct response. Code:

function checkValue () {
   var answer = document.forms[3].field1.value;
    if (answer == "Hello world!") {
         alert ("Right answer");
    }
      else {
         alert ("Wrong answer")
   }
}
The function "checkValue()" first defines a variable ('var") "answer" to be whatever the user has entered into field1. It then matches that answer against the value "Hello world!", which is in this case the response we want. A right or wrong answer triggers an alert window.

To top of page SAMPLE JAVASCRIPT QUIZ

The following example puts together most of the elements discussed so far to construct a reading comprehension self-quiz.

The entire code for this quiz is available.

The window is divided into two frames, the top frame being used to provide feedback to the student. After reading the passage, the student is asked to answer these questions on the content.

If you've followed the examples so far you should be able to make sense of the script for this quiz. This is a very basic type of exercise. JavaScript allows you to do much more than this, for example, to provide feedback on certain anticipated wrong responses, to allow only a certain number of tries, to give hints after a specific number of wrong answers, to calculate the score and the elapsed time (example). Many other formats are possible with JavaScript interactive exercises, including multiple choice.

To top of page JAVASCRIPT, "DYNAMIC HTML" AND STYLE SHEETS

JavaScript is a key ingredient in the implementation by Netscape of what is being called "Dynamic HTML" or DHTML. DHTML aims to make virtually everything on the Web page accessible to change in reaction to user actions. This includes the possibility of knowing where on the page a user has clicked. By making everything on a Web page both "hot" and changeable, a dynamic environment is being created with functionality similar to what is possible with traditional multimedia authoring systems.

The major addition to the HTML language which enables dynamic access to page elements are Cascading Style Sheets, a standard endorsed by the W3 Consortium as "CSS1". Style sheets allow Web authors to control globally--even across an entire Web site -- the appearance of elements on a Web page. This creates a "dynamic objet model" (DOM) allowing user or programmatic access to page elements. In a style sheet definition, a page element such as a header might be initially defined to display as bold and green, but through a user action or a scripted function could be changed to italics and blue. This kind of interactivity is all local, not requiring any communication with the Web server, once the page has been displayed. The full power of DHTML will be evident when style sheets are tied directly to a common scripting language, something both Netscape and Microsoft have pledged to support (ECMAScript).

To top of page Bob Godwin-Jones

JavaScript => Index / Presentation / Web Links / Next Steps || AIA Portal - ITA - WestEd