The University of Texas at Austin- What Starts Here Changes the World
Services Navigation


Javascript Rollovers

Rollovers are used to replace one image in another within a document. Rollovers are frequently used to create dynamic menus within a Web site. This is done with Javascript. While hand coding this technique with Javascript is not the easiest approach (most Web authoring programs can automate this for you), examining the Javascript code can help demonstrate some important concepts, like functions, arrays, loops, and additional object properties.

<HTMl>
<head>
<title>JavaScript Form Example</title>

<script language="JavaScript">

// Function to create empty array of images
function MakeImageArray(n) {
	for (var j=1; j<=n; j++) {
		this[j] = new Image;
	}
	return this;
}

// Create an array called imageson containing 2 blank images
// These will be the images that will display when the mouse moves over them
imageson = new MakeImageArray(2);

// Create an array called imagesoff containing 2 blank images
// These will be the images that will display when the mouse moves off
imagesoff = new MakeImageArray(2);


// Set the src property of the images in the imageson array
imageson[1].src = "home1.gif";
imageson[2].src = "search1.gif";

// Set the src property of the images in the images off array
imagesoff[1].src = "home0.gif";
imagesoff[2].src = "search0.gif";


// All of the lines above this load and cache the images while the pages loads
// so when you mouseover the image you don't have to wait for another
// image to load off the network.


// Function to switch images when the mouse moves over the image
// Each <img> tag on the page is automatically numbered and stored in 
// an array created by JavaScript called document.images.  The very first
// image tag on the page is document.images[0].  Note that the array starts
// numbering at 0.  When the function is called and passed a value of 0
// for example, it sets document.images[0].src (the source property of
// the 0 image on the page) to be the src property of the 0+1 (1) image
// in the imageson array.

function mouseon(n) {
	document.images[n].src = imageson[n+1].src;
}


// Function to switch images when the mouse moves off
function mouseoff(n) {
	document.images[n].src = imagesoff[n+1].src;
}
</script>

</head>

<body bgcolor="white">
<a href="http://www.utexas.edu" onMouseOver="mouseon(0)" onMouseout="mouseoff(0)"><img src="home0.gif" border=0></a><br>
<a href="http://www.utexas.edu/search/" onMouseOver="mouseon(1)" onMouseout="mouseoff(1)"><img src="search0.gif" border=0></a>
</body>
</html>

Test Example 6 to see what it looks like.

 


  Updated 2003 September 29
  Comments to www@www.utexas.edu