| Introduction |
In the beginning…
JavaScript dates back only a few years. In 1995 Netscape was working on a project that would enhance HTML documents called ‘LiveScript’. LiveScript shifted some of the computation and decision making from the web server that the HTML document resides on to the computer that had loaded the HTML document. Needless to say this would lighten the load on the web server, lessen the response time for certain functions of the HTML document, and broaden the possibilities of HTML design.
Later that same year, Sun and Netscape announced that the language would thereafter be known as JavaScript. Although this new name took on the flavor of the Java programming language, there is a huge difference between the two. On the surface, you will notice that both are similar – they both take on the look and syntax of C and C++, but that is about the only thing similar between the two. They use two totally different compilers – methods for executing each line of code.
From this handout on…
Since JavaScript is coded straight into an HTML document we will start out by looking at the parts of the HTML document. Understanding how the HTML document is put together is essential in understanding how JavaScript can access the parts of your HTML document. You will see HTML documents in a whole new light, especially if you are new to HTML scripting or have been using an HTML editor to create your documents.
Once you have a pretty good grasp on the makeup of an HTML document, we will look at the role JavaScript plays in your HTML document. You will see how JavaScript accesses the parts of your HTML document and how it can modify those parts. You will look at working JavaScript examples and identify what those examples are doing and how they are doing it.
There is nothing like hands on experience. You will be given JavaScript examples and asked to recreate them in an HTML document of your own. After you have regenerated these examples you will be ready to move on to the next step. In my opinion, one of the best ways to learn how something is suppose to work is to find and correct errors. You will also be given incomplete examples as well as complete examples that have bugs (errors) in them. Finally, you will be given a problem which you must modify a working JavaScript so that it works in a different way.
This should be a lot of fun. Enjoy the workshop and don’t be afraid to be creative and most importantly don’t be afraid to ask questions. It is critical that you have a good understanding of the first part of the workshop before you can move on.
| Understanding the HTML Document |
HTML (Hyper Text Markup Language) scripting is a way to create documents which, when viewed through software that interprets HTML, are displayed by the tags you have set. What do I mean by tags? You will encounter the terms: tag, open tag, and close tag often within this document. Basically, in simplest terms, a tag gives you the ability to format text, images, objects, etc… as you create your HTML document. There are many HTML tags that you can use and they come in two types: an open tag and a close tag. You will use the open tag as a starting point within your document. The effects (attributes/methods) of that tag will continue until the appropriate closing tag is encountered. Here is a simple example to help clarify what was just stated:
<I>
<U>
<B>
Bold and
</B>
underlined.
</U>
</I>
where:
<I> :open italics tag
<U> :open underline tag
<B> :open bold tag
</B> :close bold tag
</U> :close underline tag
</I> :close italics tag
produces:
Bold and underline.
Notice that all of the closing tags include a slash (/). Also notice how the bold formatting stops after the word ‘and’ because of the closing bold (</B>) tag.
It is not to hard to view tags as formatting tools, but now I would like to get you to think of tags as objects. An object is nothing more than something that has characteristics (attributes) and may perform actions (methods). Objects may contain other objects.
Got you confused yet? Let me try to clear me try to clear some things up. Think of your entire HTML document as an object. The open tag for the HTML documents is: <HTML> and the close tag is </HTML>. Within the <HTML> object (we usually term the HTML object as the ‘document’ object) you may have an image object. In other words, you are putting an image on your web page. The tag you have used in the past is the <IMG> tag. An example might be:
<IMG SRC=”logo.jpg” ALT=”ABC Company Logo” NAME=”logo”>
Now try to look at this tag as an object, the image object. Note that this image object has three attributes:
SRC: Name of the actual image file
ALT: Text to be displayed by text only browsers or displayed when the mouse passes over the image.
NAME: The name given to this image object. Any object and attributes of that object can be accessed and modified by your JavaScript.

To access one of the objects you can do so by working your way ‘down’ to the object and accessing it by name. To check the status of a checkbox input object named ‘send_more_info’ in a form named ‘subscribe’, I could type in the following:
if(window.document.subscribe.send_more_info.checked) … Notice how we work down from the window object to the checkbox object. Just a note: the window object is ‘understood’, which means that it could be left out and the above statement would still have been valid. It is included for syntax and will be visited again when we discuss using JavaScript to access other browser windows.
Accessing objects can be done using array notation as well. For example, if we have two forms in the same HTML document, we can access them by using the form[x] notation. If subscribe is the first form in our HTML document, the ‘if’ statement could be rewritten as follows:
if(window.document.form[0].send_more_info.checked) …
| Inserting Javascript |
I have mentioned that JavaScript can access an object within your HTML document. The next questions are ‘where do I put the JavaScript?’ and ‘how does it access the HTML document objects?’. The JavaScript code can be placed anywhere within your HTML document, but is usually placed within the head tags <HEAD></HEAD>. Remember that the general format of your HTML document is:
| <HTML>
<HEAD> <TITLE>ABC Company</TITLE> <SCRIPT> <!--- Put your JavaScript here... // --> </SCRIPT> </HEAD> <BODY> </BODY> </HTML> |
The line just below the script tag appears to be an HTML comment; it is. The JavaScript interpreter knows to ignore that line and continue on with the next. Why the comment? The browser recognizes the comment and does not display your JavaScript code to screen. The close comment is the - ->. Notice the double slash (//) before the close comment. This is the syntax for commenting a line within your JavaScript code.
To have your JavaScript access your HTML document objects the dot(.) notation is used. It is basically a drill-down method. Let’s revisit our image example:
<IMG SRC=”logo.jpg” ALT=”ABC Company Logo” NAME=”logo”>
To access the SRC attribute of the image you might have a line in your JavaScript like this:
ImageFile = document.logo.src
I am using the name of the image object, which is logo, to store the SRC attribute of the image object in the variable ‘ImageFile’.
JavaScript is event-driven which means that some event had to have taken place to initiate the JavaScript code. Such events might be clicking a button, text or image; loading/exiting an HTML document, passing the mouse over an image, entering text, etc… There are a number of events that can take place; we will look at some of the more common events in our examples.
Off to some examples
| Alert and Confirm Boxes |
This JavaScript example contains two JavaScript functions.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function done()
{
alert("The Page has Finshed Loading.")
}
function confirmUser()
{
if(confirm("Do you want to go to MTSU's Homepage?"))
{
location="http://www.mtsu.edu";
}
}
// -->
</SCRIPT>
</HEAD>
<BODY onLoad="done()">
<FORM NAME="converter">
<CENTER><H2>Example 1a</H2></CENTER>
<INPUT TYPE="button"
NAME="Button3"
VALUE="MTSU Home Page"
onClick="confirmUser()">
</FORM>
</BODY>
</HTML>
|
The first function is a simple Alert box that displays when the page is loaded. Notice the onload method located in the <BODY> tag. The second function activates a Confirm box when the DailyNewsJournal button is clicked. The alert box is displayed using the alert function called within done(). The confirm box is created using the confirm function within the if statement of confirmUser(). The confirm function returns TRUE when the OK button is clicked on the confirm box and FALSE when the Cancel button is clicked.
| Alert Boxes - Activated Inline |
This example is similar to the previous one. It is included to demonstrate how some of the events can be handled inline.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function alertUser()
{
alert("Ha Ha!!");
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="converter">
<CENTER><H2>Example 1b</H2></CENTER>
<BR><HR><BR><BR>
<INPUT TYPE="button"
NAME="Button1"
VALUE="Click Me!!"
onClick="window.alert('Ouch!')">
<BR><BR>
<INPUT TYPE="button"
NAME="Button2"
VALUE="No!! Click Me!!"
onClick="alertUser()">
</FORM>
</BODY>
</HTML>
|
|
|
Note Button1 handles the event inline while Button2 calls the alertUser() JavaScript function.
| Accessing/Modifying Data in a Form Text Box |
This example is a little more involved. We start using the HTML page structure to access the input text boxes of the form.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function LowerMe()
{
document.e1c.output.value = document.e1c.input.value.toLowerCase();
}
function UpperMe()
{
document.e1c.input.value = document.e1c.input.value.toUpperCase();
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="e1c">
<CENTER><H2>Example 1c</H2></CENTER>
<BR><HR><BR><BR>
<INPUT TYPE="text"
NAME="input"
VALUE="Insert text here"
onChange="UpperMe()"><BR>
<INPUT TYPE="text"
NAME="output"
VALUE=""><BR>
<INPUT TYPE="button"
NAME="Button4"
VALUE="Convert"
onClick="LowerMe()">
</FORM>
</BODY>
</HTML>
|
|
|
First of all, lets look at how the parts of the HTML page are accessed. In the LowerMe() function, notice how we are ‘drilling’ (working our way) down to the value attribute of the text input box named input. At the outermost level we specify document for our HTML document. Then, within document we specify converter, the name of the form. Next we specify input, which is the name of the first input text box. Finally, we specify value, an attribute of input. Notice how we are assigning to value the lower case of itself. When will this happen? It will happen whenever you change the value of input and hit your tab key, return key, click somewhere else, etc…, because of the onChange() method found in input. Look at the UpperMe() function and try to follow how it ‘drills’ down and how it is accessed.
Two things are happening here. First, whenever you type something in input, what you typed in will be forced lowercase. Secondly, whenever you click the Button4 button, whatever has been typed in input will be assigned to the input text box named output and forced as uppercase.
The toLowerCase() and toUpperCase() methods found in functions LowerMe() and UpperMe() respectively are standard JavaScript Language methods.
| Accessing Data in a Form Checkbox |
In this example the status of objects on the form are checked. Depending on the status of the object an action happens. Like the previous example we are ‘drilling’ down to the values of the objects. Again, try to figure out how the values of the different objects are accessed and where they are called.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function inspectBox()
{
var alertString;
if(document.converter.checkThis.checked)
{
alertString = document.converter.checkThis.value +
" - The box is checked";
}
else
{
alertString = document.converter.checkThis.value +
" - The box is NOT checked";
}
alert(alertString);
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="converter">
<CENTER><H2>Example 1d</H2></CENTER>
<BR><HR><BR><BR>
<INPUT TYPE="checkbox"
NAME="checkThis"
VALUE="Rub a dub dub">Check Here<BR>
<INPUT TYPE="button"
NAME="Button5"
VALUE="Inspect Box"
onClick="inspectBox()">
</FORM>
</BODY>
</HTML>
|
|
|
There are two input objects on this form. The first is the checkThis checkbox and the second is the Button5 button. Clicking Button5 calls the inspectBox function. The ‘if’ statement in that function handles the action depending on the status of the checkbox.
| Accessing Data in Form Radio Buttons and Select Boxes |
In this example we are again checking the status of different input objects in the HTML document. It was mentioned earlier that objects could be accessed using an array notation; we are taking advantage of that in this example. This example also introduces the keyword ‘this’.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function searchEngine()
{
var i;
for (i=0 ; i<document.converter.engine.length ; i++)
{
if(document.converter.engine[i].checked)
{
break;
}
}
location = document.converter.engine[i].value;
}
function searchEngine2(whichEngine)
{
location = whichEngine.options[whichEngine.selectedIndex].value;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="converter">
<CENTER><H2>Example 1e</H2></CENTER>
<BR><HR><BR>
<BR><B>Pick a Search Engine</B><BR>
<INPUT TYPE="radio"
NAME="engine"
VALUE="http://www.yahoo.com"
onClick="searchEngine()">Yahoo<BR>
<INPUT TYPE="radio"
NAME="engine"
VALUE="http://www.lycos.com"
onClick="searchEngine()">Lycos<BR>
<INPUT TYPE="radio"
NAME="engine"
VALUE="http://www.altavista.com"
onClick="searchEngine()">Alta Vista<BR>
<INPUT TYPE="button"
NAME="Button6"
VALUE="Go to Site"
onClick="searchEngine()">
<BR><HR><BR>
<BR><B>Pick a Search Engine</B><BR>
<SELECT NAME="engine2" onChange="searchEngine2(this)">
<OPTION VALUE="http://www.yahoo.com">Yahoo
<OPTION VALUE="http://www.lycos.com">Lycos
<OPTION VALUE="http://www.altavista.com">Alta Vista
</SELECT>
</FORM>
</BODY>
</HTML>
|
|
|
First, let’s look at the use of the array notation. Notice that all the radio input objects have the name ‘engine’. The function searchEngine() is called when ever the radio button is clicked. In that function a for loop runs from 0 to engine.length where length is automatically set to the number of ‘engine’ radio buttons.The engine array index is that of the for loop index.
Next, let's look at the keyword ‘this’. In the engine2 select input object the method onChange calls the function searchEngine2() with the ‘this’ parameter. ‘this’ refers to the current object including all the attribute values of that object and the object’s place in the HTML document structure. Notice in the function searchengine2(), the variable whichEngine receives the engine2 object. Also notice that when accessing the value attribute of engine2 the ‘drill-down’ structure is missing. Again, this is because the ‘this’ reference included where engine2 was located within the HTML document.
| Creating Multiple Windows and Communicating among Them |
Are you ready to take JavaScript a step farther? At the beginning of this document a reference was made to the window object. With JavaScript you can create browser windows, destroy browser windows and have data sent back and forth between two windows.This is demonstrated in the following example.
<HTML>
<HEAD>
<TITLE>Main Document</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function makeNewWindow()
{
newWindow = window.open("subwindow.html",
"window_name",
"height=300,width=600,toolbar,scrollbars,resizable");
}
function closeNewWindow()
{
if (newWindow)
{
newWindow.close();
}
}
//-->
</SCRIPT>
<BODY>
<FORM>
<CENTER><H2>Example 2</H2></CENTER>
<BR><HR><BR><BR><BR>
<INPUT TYPE="button" VALUE="Create New Window" onClick="makeNewWindow()"><BR>
<INPUT TYPE="button" VALUE="Close New Window" onClick="closeNewWindow()"><BR>
Text coming from subwindow:
<INPUT TYPE="text" NAME="entry"><BR>
</FORM>
</BODY>
</HTML> |
|
|
There are three input objects in this HTML Document. The first is the “Create New Window” button. Clicking it calls the makeNewWindow() function. Within that function a new window object called newWindow is created using the window method open. The second input object is the ‘Close New Window” button. This simply calls the closeNewWindow() function to execute the close window method. The last input object is a text input box. As we will see below, the window created in this example will send information to this input box. This could be very helpful if you have HTML documents with similar forms. You could pass data from document to document saving the user from having to retype common fields, i.e. Address, phone number, name, etc…
Here we show the contents of the HTML document placed in the window created above.
<HTML>
<HEAD>
<TITLE>A Subdocument</TITLE>
</HEAD>
<BODY BACKGROUND="http://www.mtsu.edu/~ccurry/pix/bg_purple.jpg">
<CENTER>
<FONT SIZE=+3 COLOR=coral>Please wait</FONT><BR>
<TABLE BORDER=5>
<TR>
<TD> <IMG SRC="http://www.mtsu.edu/~ccurry/pix/eyeflash.gif" HSPACE=0 VSPACE=0> </TD>
</TR>
</TABLE>
<FORM>
<FONT COLOR=coral>
<B>Enter Text to be displayed in the Main Window:</B>
</FONT><BR>
<INPUT TYPE=text onChange="opener.document.e2.entry.value=this.value">
<INPUT TYPE=submit VALUE="Update Main Window" onClick="window.close()">
</FORM>
</CENTER>
</BODY>
</HTML>
|
Here, there are two inline methods being processed. First, whatever is typed in the input box will be assigned to the input box named ‘entry’ in the document of the example above. Notice the reference to opener. This is how you can access the window that created this window. The array notation (forms[0] and the keyword ‘this’ are revisited.
Finally, the clicking the ‘submit’ button will close this window and take you back to the window that created it.
| Using a Select Box to Change an Image. |
You can access objects other than input objects (text boxes, radio buttons, and check boxes). In this example we will use the select box to update an image.
<HTML>
<HEAD>
<TITLE>Image Object</TITLE>
<SCRIPT>
<!--
image0=new Image();
image1=new Image();
image2=new Image();
image3=new Image();
image4=new Image();
image5=new Image();
image6=new Image();
image7=new Image();
image8=new Image();
image9=new Image();
image0.src = "http://www.mtsu.edu/~ccurry/pix/planets/solar_system.gif";
image1.src = "http://www.mtsu.edu/~ccurry/pix/planets/mercury.gif";
image2.src = "http://www.mtsu.edu/~ccurry/pix/planets/venus.gif";
image3.src = "http://www.mtsu.edu/~ccurry/pix/planets/earth.gif";
image4.src = "http://www.mtsu.edu/~ccurry/pix/planets/mars.gif";
image5.src = "http://www.mtsu.edu/~ccurry/pix/planets/jupiter.gif";
image6.src = "http://www.mtsu.edu/~ccurry/pix/planets/saturn.gif";
image7.src = "http://www.mtsu.edu/~ccurry/pix/planets/uranus.gif";
image8.src = "http://www.mtsu.edu/~ccurry/pix/planets/neptune.gif";
image9.src = "http://www.mtsu.edu/~ccurry/pix/planets/pluto.gif";
function changeImage()
{
document.thumbnail.src = document.planet.pictureSet.options[document.planet.pictureSet.selectedIndex].value;
}
//-->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=black text=dodgerblue>
<CENTER>
<FORM NAME=planet>
<H2>The Solar System</H2>
<BR><HR><BR>
<IMG SRC="http://www.mtsu.edu/~ccurry/pix/planets/solar_system.gif" NAME="thumbnail"><BR>
<SELECT NAME="pictureSet" onChange="changeImage()">
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/solar_system.gif">Solar System
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/mercury.gif">Mercury
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/venus.gif">Venus
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/earth.gif">Earth
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/mars.gif">Mars
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/jupiter.gif">Jupiter
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/saturn.gif">Saturn
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/uranus.gif">Uranus
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/neptune.gif">Neptune
<OPTION VALUE="http://www.mtsu.edu/~ccurry/pix/planets/pluto.gif">Pluto
</SELECT>
</FORM>
</CENTER>
</BODY>
</HTML>
|
|
|
There are two select boxes named pictureSet1 and pictureSet2; they both make a call to loadCached(). As parameters, the select object itself is sent (using the this keyword) as well as the name of the image object it is associated with; either thumbnail1 or thumbnail2.
| Fill in the Missing Pieces |
Now that you have had a chance to look at some examples and have recreated some of them lets look at an example that has a few pieces missing. Fill in the pieces and try to get it to work.
<HTML>
<HEAD>
<TITLE> Sum Maker </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function addIt()
{
var value1 = document.______.value;
var value2 = document.______.value;
document.adder.output.value = parseInt(value1) + parseInt(value2);
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<CENTER><H2>Example 5</H2></CENTER>
<H3>Enter 2 numbers and Click the add button</H3>
<FORM name=adder>
<INPUT TYPE="text" NAME="inputA" VALUE="0" SIZE=4><BR>
<INPUT TYPE="text" NAME="inputB" VALUE="0" SIZE=4>
<INPUT TYPE="button" VALUE="Add" onClick="addIt()">
<HR WIDTH=90 ALIGN=left>
<INPUT TYPE="text" NAME="______" SIZE=6> <BR>
</FORM>
</BODY>
</HTML>
|
In the script above there are three pieces missing. Fill in the three pieces and the script should work just fine. Also note the use of parseInt() this is a method used to get the ‘value’ of a string number.
| Lets go Bug Hunting |
There are two bugs in the script below. Try to find them and get it to work.
<HTML>
<HEAD>
<TITLE> Planet Order </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
var thePlanets = new Array(10)
thePlanets[0] = "Mercury"
thePlanets[1] = "Venus"
thePlanets[2] = "Earth"
thePlanets[3] = "Mars"
thePlanets[4] = "Jupiter"
thePlanets[5] = "Saturn"
thePlanets[6] = "Uranus"
thePlanets[7] = "Neptune"
thePlanets[8] = "Pluto"
var theDistance = new Array(10)
theDistance[0] = "First"
theDistance[1] = "Second"
theDistance[2] = "Third"
theDistance[3] = "Fourth"
theDistance[4] = "Fifth"
theDistance[5] = "Sixth"
theDistance[6] = "Seventh"
theDistance[7] = "Eighth"
theDistance[8] = "Nineth"
|