Javascript Samples

 
 
[prev][home]
 

First, what is Javascript? Javascript is a programming language that Netscape and Internet Explorer know how to interpret. Because they can understand it, we are able to write little programs that are actually contained in the Web page that we are writing. These programs can change what we see in the page, or how the page interacts with the viewer.

To actually use it, in the long run we would have to all learn how to be programmers. But that's a bit much to expect for a workshop like this, so we'll just look at a couple of fun applications that we can "cut and paste" to use: first, a Goto Select Button, second, rollover buttons/images (note that you can do these automatically using DreamWeaver!), and third, simple quiz checking.

  GoTo Select Buttons

An example "goto" select button:
This is accomplished with remarkable simplicity. To do it, we need to create a select form element which uses a javascript property of the window to change the window location when the value of the form is changed:
  <form>
  <select
  onChange="window.location = this.options[this.selectedIndex].value;">
    <option value="10javascript.html"> you are now here
    <option value="index.html"> goto workshop home
    <option value="08resources.html"> goto resources.html
  </select>
  </form>
Replace the 10javascript.html, index.html, and 08resources.html with the URLs of the pages that you want to go to. The text to the right of the <option> tags, obviously, is that which is displayed in the element. Do you believe me? Select view -> page source on your browser and find these in this page. You'll have to scroll down a bit to find the example form element.

top | quiz
  Image RollOvers

An example of "image rollovers":
home
resources
Note that Dreamweaver will set all of this up for you. Read on for an explanation of just how it does it!
This is a little trickier. Three things are really going on here: (1) each image is a link, (2) a mouseover event swaps the image for a different image when we run the mouse over the image, and (3) a mouseout event swaps the image back when we move the mouse off the image. Let's take each of these in turn:

(1) Making the image a link can easily be done with the HTML

  <a href="index.html"><img src="images/button1off.gif"></a>
which displays as . To get rid of the blue border, add a border="0" attribute to the image, and if we're being really good about the HTML we're doing, we should also specify the height and width of the image so that the browser knows how much space to allocate to the image (I found the size out by using gimp, which is like Photoshop; any old image (or web) editor should tell you this if you look in the right place):
  <a href="index.html"><img src="images/button1off.gif" border="0" 
    height="20" width="80"></a>
displays as:

So far, so good. Now, let's add the
(2) mouseover and (3) mouseout events. No problem: we name the image so that the javascript can change the image, and add the event handlers to the anchor tag:

  <a href="index.html" onMouseOver="imageOn('1');"
   onMouseOut="imageOff('1');"><img src="images/button1off.gif" 
   border="0" height="20" width="80" name="button1"></a>
Note: (i) we've made the name of the button "button1", and (ii) the onMouseOver and OnMouseOut handlers call the javascript functions imageOn and imageOff with the number of the button. Thus the HTML code that produced the example above is that shown below.

<table cellpadding="0" cellspacing="0" border="0">
  <tr>
    <td><a href="index.html" onMouseOver="imageOn('1');"
	onMouseOut="imageOff('1');"><img alt="home"
	src="images/button1off.gif" height="20" width="80" name="button1"
	border="0"></a></td>
  </tr>
  <tr>
    <td><a href="08resources.html" onMouseOver="imageOn('2');"
	onMouseOut="imageOff('2');"><img alt="resources"
	src="images/button2off.gif" height="20" width="80" name="button2"
	border="0"></td>
  </tr>
</table>
I wrapped the images in a table with no border or spacing to eliminate spaces between them and keep them together on the page; in this case, it probably isn't necessary. Finally, what's the javascript for this? The code I used is the following:
<script language="javascript">
<!-- //
  // ------- javascript for rollovers --------
  // variable definitions for rollovers
  var numbuttons = 2;           // change the "2" to the number of buttons
  var height = 20;              // change the "20" to the height of the buttons
  var width = 80;               // change the "80" to the width of the buttons
  var imageDir = "images";      // directory where images are found
  var imageName = "button";     // name of images; appending the button number &
                                //   "off.gif" gives the "off" button; appending
                                //   the number and "on.gif", the "on" button
  // preload images
  var onbutton = Array(numbuttons+1);   // all the rest of this should 
  var offbutton = Array(numbuttons+1);  //    take care of itself
  for ( var i=1; i<num; i++ ) {
      onbutton[i] = new Image(width,height);
      onbutton[i].src = imageDir + "/" + imageName + i + "on.gif";
      offbutton[i] = new Image(width,height);
      offbutton[i].src = imageDir + "/" + imageName + i + "off.gif";
  }

  // function to turn images on
  function imageOn(imgNum) {
      eval("document.button" + imgNum).src = onbutton[imgNum].src;
  }
  // function to turn images off
  function imageOff(imgNum) {
      eval("document.button" + imgNum).src = offbutton[imgNum].src;
  }
  // ----- end javascript for rollovers ------
  // -->
</script>

NOTE:

  1. This requires that you name your buttons "button1", "button2", and so on.
  2. It requires that you plug in the number of buttons you have in the "numbuttons" line.
  3. It requires that you plug in the height of your buttons in the "height" line.
  4. It requires that you plug in the width of your images in the "width" line.
  5. It requires that you plug in the directory and name of your buttons in the "imageDir" and "imageName" lines.
  6. It requires that your "on" buttons be named the name you just gave with button-number and "on.gif" appended, and similarly for "off" buttons -- so if you said your image directory was "images/buttons" and your button name was "dicey-roller", then the script assumes that the "off" image for button 4 is
    images/buttons/dicey-roller4off.gif
Check it out in the source code for this page. No, really.

top | goto

  Simple Select Quiz Checking

An example "select button" quiz:
Coding HTML by hand is:
My truthfulness is:
Number right:
Number wrong:
Here we have a series of questions, all of which have multiple choice answers provided by the select form elements shown. When the user selects an answer, the javascript code checks their answer, increments the number of right/wrong answers they have given, and displays a helpful message regarding their success. Again, there are two parts to this: the HTML for the form, and the javascript supporting it. First, the HTML:
  <form name="quiz">
  Coding HTML by hand is:
  <select onChange="checkAnswer('1');" name="problem1">
    <option value="0"> [no answer]
    <option value="1"> euphoric
    <option value="2"> boring
  </select>
  My truthfulness is:
  <select onChange="checkAnswer('2');" name="problem2">
    <option value="0"> [no answer]
    <option value="1"> questionable
    <option value="2"> impeccable
  </select>
  Number right: <input type="text" name="numberright" size="1" value="0">
  Number wrong: <input type="text" name="numberwrong" size="1" value="0">
  <center>
  <img src="images/blank.gif" height="50" width="100" name="rightwrong">
  </center>
  </form>

What's IMPORTANT here?
  1. Name the form tag "quiz": <form name="quiz">
  2. Name each select "problemN", and have it call the "checkAnswer" function when it changes: <select name="problem1" onChange="checkAnswer('1');">. The number in the (' ') for checkAnswer must be the problem number.
  3. Make the options on the select elements have "values" 0, 1, 2, etc., as shown.
  4. Make the first (default, not correct) entry of each select have value 0.
  5. Include a text form element named "numberright" and another named "numberwrong".
  6. Include an image named "rightwrong".

Ok, how about the javascript? The javascript for this (again, put this in the head section of your document) is the following:

  <script language="javascript">
  <!-- //
    // ----- javascript for game tallying -----
    // array of correct answers
    var correct = new Array(1,2);

    var rightwrongHeight = 50;            // height of right/wrong/blank images
    var rightwrongWidth = 100;            // width of right/wrong/blank images
    var rightSource = "images/right.gif"; // right image
    var wrongSource = "images/wrong.gif"; // wrong image
    var blankSource = "images/blank.gif"; // blank image

    var delay = 3;                  // # seconds before swapping image to blank

    var right = new Image(rightwrongWidth,rightwrongHeight);
    var wrong = new Image(rightwrongWidth,rightwrongHeight);
    var blank = new Image(rightwrongWidth,rightwrongHeight);
    right.src = rightSource;
    wrong.src = wrongSource;
    blank.src = blankSource;

    var numright = 0;
    var numwrong = 0;

    // initialize number right and wrong
    function initRightWrong() {
	document.quiz.numberwrong.value = 0;
	document.quiz.numberright.value = 0;
    }

    function checkAnswer(probNum) {
	if ( eval("document.quiz.problem" + probNum).selectedIndex !=
	     correct[probNum-1] ) {
	    document.rightwrong.src = wrong.src;
	    numwrong++;
	    document.quiz.numberwrong.value = numwrong;
	} else {
	    document.rightwrong.src = right.src;
	    numright++;
	    document.quiz.numberright.value = numright;
	}
	setTimeout("document.rightwrong.src=blank.src;", delay*1000);
    }

    // ----- end of javascript for game tallying -----
    // -->
  </script>

NOTE: to use this, you need to
  1. put the correct answers, in order, in the Array() called correct,
  2. set the height, width, and names of the right, wrong, and blank images. Stealing my blank image would be fine.
  3. set the delay in seconds that you want before the 'right' or 'wrong' message image vanishes.
One more thing: to be sure that you start with the numberright and numberwrong form elements looking right, you might want to change your <body> tag to:
  <body onLoad="initRightWrong();">

Side note: this isn't a particularly secure quiz: anyone looking at the page source can find out what the right answers are.

top | goto | rollover



Gavin's HHMI 02 Web Workshop: Javascript Samples
Last Modified: Fri May 31 11:04:44 EDT 2002
Comments to glarose@umich.edu
©2002 Gavin LaRose, UM Math Dept