Lab 07: Algorithms—Programming JavaScript Statements

Goal

The purpose of this assignment is get experience writing JavaScript applications. Key ideas are:

Resources: The lab extends the forms concepts of Lab 6 and the JavaScript programming ideas.

Note: If you chose to install the Firefox Web Developer toolbar at school, be aware that the computer labs will not "remember" that you installed it and you will install it for every lab session..

On home computers, you need to install it only once.

Getting Started

Create a HTML Web page with the following look: The background is gold, and the text is brown. Save the file as lab7.html on the desktop. When you’re finished, it’ll go in a lab7 folder under your fit100 directory on Dante.

<html>

<head>

   <title>Worth Your Weight</title>

</head>

<body style="background-color:gold; color:brown;">

   <h1 style="font-family: helvetica; text-align: center;">Gold </h1>

   <p style="text-align: center;"> This is a Web page built for Lab 7.</p>

</body>

</html>

 

Computing Your Weight in Gold

Gold was selling for $748.10 per troy ounce on October 12, 2007. We want to compute how much each of us would be worth if we were “worth our weight in gold,” as the old saying goes.

A. Using your knowledge of forms, create a request to the user to enter his or her weight. The request should be followed by a text box with the name weight, and size of 5. On the next line should be the text reporting the result, followed by another textbox for the output. Its name should be out and its size should be 7. Your page should look as follows:

B. Next define the event handler for the weight computation. Define the onChange event handler to compute the user’s weight in gold. There are 12 troy ounces in each pound and the price of gold is $748.10 per troy ounce. (Just use the number, don’t include a $ symbol!) Multiply the three values together and assign it as the value for the output window, that is, out.value.

C. Check your result with a value of 1 lb. Nothing will happen until you press TAB to move away from the input box. That user action will activate the onChange event handler. Verify that your display shows 12 times the price of an ounce of gold, $8977.20.

Debugging your code

Hopefully, you haven’t made any errors in your programming thus far, but chances are that you have. Two helpful tools are available only in Firefox. To help you with your HTML code, install the Web Developer Toolbar. To help you with JavaScript, use the Javascript console, which allows you to test Javascript and displays any Javascript errors that have occurred on your webpage.

JavaScript Error Console

Only Firefox browsers have the Javascript console, so make sure you’re not trying to do this in Internet Explorer. If you are, close the window, right-click on the lab7.html icon on your desktop, select “Open with…” and open it with Firefox.

The Javascript console is located in Tools > Javascript Console for Firefox. It should be blank, as the image below shows. If it is not, it either means you have an error on your page, there was an error on your page but you fixed it (the Javascript console doesn’t automatically erase old error messages) or these errors are from another page that you opened in this browser (yes, even professionally designed webpages have Javascript errors sometimes). In any case, you can hit “clear” to clear it for now.

Now, let’s introduce an error into your code intentionally to see what happens.

Let’s say your error is that you misspelled “out” as “ot” in out.value which is your onChange event handler. Make the change to ot.value now. Do not change the spelling of “out” anywhere else, only change that one instance of it.

Save your page.

Reload your page in your browser. Check the Javascript console, it should still be empty.

Now, type in your weight and see if your form gives you your weight in gold. It shouldn’t, because you’ve intentionally placed an error in your Javascript.

Now look at the Javascript console. It should have one error saying “ot is not defined”. This basically means that you are asking the browser to do something with “ot” but the browser can’t find anything named “ot.” In our case, that’s because there IS nothing named “ot”, the text box we’re looking for is named “out.”

Often, there will be a line number as well. Check the line number and find the matching line in your code, look for the error, and fix it. Here, the problem was obviously a misspelling. In the future, there may be other reasons for things being “not defined” but you’ll discover that for yourself as you practice more Javascript.

Be sure to fix your error before you move on.

Display Four Pictures

Grab the liberty.jpg image and place it on your desktop. We want to display this image four times in a row on the page, which uses the usual tag:

<img src="liberty.jpg">

Copy and paste this tag into the file four times so the images line up in a row.

Display Four More

We will now write JavaScript commands to insert a tag into the HTML file. This common operation is used to build Web pages on the fly. (We won’t be doing that quite yet, but we want the knowledge now.)

To write JavaScript, insert the tags after the images in your Web page:

<br />
<script type="text/javascript">

</script>

Inside of these scripttags, the browser will understand the commands as JavaScript; it will NOT understand HTML inside the tags. Between the opening and ending script tags, write the line

document.write('<img src="liberty.jpg">');

This command tells JavaScript to write the <img …> tag into the HTML file at the position where the <script> tag is placed. That will cause a fifth copy of the image to be placed on the page. Replicate the document.write line 3 more times so it appears a total of four times inside the <script> tags.

The use of document.write had the same affect as our explicit use of the <img …> tags, because after the document write commands have been performed by the JavaScript interpreter, the result is the same: four more <img …>source lines.

This works because when the browser processes the HTML, it scans the file looking for JavaScript. It does the JavaScript first, which for us is to place four more copies of the image, and then it displays the resulting HTML. See pp. 578-579 in the textbook for a fuller explanation.

A Tweak

The first set of images had a break between each image, but the second group produced by document.write did not. This is because our command

document.write('<img src="liberty.jpg">');

had no spaces after the <img …> tag. If we insert a space after it,

document.write('<img src="liberty.jpg">');

they will look the same. (Actually, the original <img …> tags were on separate lines, and it wasn’t actually a space but the return that created the white space that separated the pictures.) Make the correction and see that it has the proper effect. And, at this point, add a <br /> to the end of the final document.write. Make sure you put that <br> in the right place so that it actually gets interpreted through the Javascript document.write!

Get Pictures

In the next part we will use four .gif images designed to spin around in an animation. Download these four images to your Desktop and then upload to your fit100/lab07 folder:

Composing File Names

One great advantage of using JavaScript to write text into our HTML files is that we can “compute” file names. We illustrate this simply today, but it will be the basis for animation and other interesting Web pages later.

Declare a variable i right after the opening <script> tag and before the five document.writestatements:

var i;

After the four document.write statements, type in

i = 0; document.write("<img src=New_" + i + ".gif>");

The first of these instructions sets the variable i to 0, i.e. it gives i the value zero. The second is like the earlier document.write statements, except that this one creates the file name using concatenation (+) and the variable i. So, because using a variable is like using its value explicitly, we create the name new/New_0.gif, which is the first of the four files we loaded. Try it out and see that you get the following:

Other Orientations

Now, replicate the line three more times, changing the value assigned to i each time to one number larger:

i = 1;
document.write("<img src=New_" + i + ".gif>"); i = 2; document.write("<img src=New_" + i + ".gif>"); i = 3; document.write("<img src=New_" + i + ".gif>");

and notice that the result is

What happened? Each time the value of i is changed, the “composed” file name is different because it uses the new value. So, the same document.write command can create different file names using composition.

Because we are just learning JavaScript, the example isn’t very compelling. We could have just typed the different names. But, soon, we will do the incrementing of the i value automatically, and then the power of composing file names with JavaScript will pay off.

Validating Your Code

Validating this code is nearly impossible unless other JavaScript methods are used. So relax about validation for this lab.

Extra Credit

For 6 points extra credit, make the images spin continuously.

  1. Declare an array for the four images at then end of the header script after the calcWeight function:
    	    var adImages = new Array(4)  //declare the new array (Array must have a capital A)
    		for (j=0;j<4;j++)            //create a four loop to add the four images to the array
        	{
        	    	adImages[j] = "New_" + j + ".gif"; //use the increment variable as part of the image name
        	}
  2. Set up the rotation function by adding these lines at then end of your script:
        	var thisAd = 0;       //initialize array index 
        	function rotate()     //start function that swaps in, or rotates, images in place
        	{
        	    	thisAd++;
        	    	document.getElementById("adBanner").src = adImages[thisAd]; //uses DOM methods to find the image
          	    setTimeout("rotate()", 1000);    //1000 sets up the speed of rotation; experiment!
        }  
  3. Go back up to the end of the header script after the calcWeight function, and add this line to start the rotation:
    	    window.onload = rotate; //loads the rotate function and starts it as soon as the page loads
  4. Place the first image on the page by adding this code to the body section. Adding an id allows document.getElementById to find the starting image that will be replaced in the rotate function:
  	    <p><img src="images/new/New_0.gif" id="adBanner" alt="Ad Banner" /></p>
  1. The images will rotate through once. Open up the file in Firefox to check that it works.

  2. Make it rotate continuously by adding these lines to your rotate function after thisad++:
    if (thisAd == adImages.length) 
    {
    thisAd = 0;
    }
  3. Change the speed of rotation by changing 1000 to 2500 in your rotate function.

Grading Rubric Updated!

This lab is worth 20 points and 6 points extra credit are available.

 
Item Points
Form tags 2
Two named textboxes 4
Four coins 4
Eight coins 4
Four "new" images 4
Weight in gold in outbox 2
Extra credit banner 6

Turn in

Due Date: Tuesday, February 19, before 5:00 pm. Do not work on your lab after the turn-in date. If the date stamp on the file is after the turn-in date, it will be considered late.