Image Rollovers

Image rollovers are a popular way of making a website appear more dynamic. Image rollovers are often used for highlighting buttons when users hover over them with using their mouse. Of course, there are plenty of other uses for image rollovers too, because the basic principal of image rollovers is that you simply swap one image with another image.

Image Rollover Example

Here's a basic image rollover example.

<script type="text/javascript">
// Pre load images for rollover
if (document.images) {
	smile = new Image;
	nosmile = new Image;

	smile.src = "/pix/smile.gif";
	nosmile.src = "/pix/nosmile.gif";
function swapImage(thisImage,newImage) {
	if (document.images) {
		document[thisImage].src = eval(newImage + ".src");
<a href="/html/codes/" onMouseOver="swapImage('jack','smile')" onMouseOut="swapImage('jack','nosmile')"><img src="/pix/nosmile.gif" width="100" height="100" border="0" name="jack"></a>

Explanation of the Code

In this example, we use the ordinary HTML <img> element to embed an image onto the web page, and we link it to another web page using the <a> tag.

The JavaScript part of the code swaps one image with another whenever the user hovers over the image. Because the two images are different (i.e. one has a smile the other doesn't), the image "smiles" when you hover over it. We do this using the onmouseover event, which is one of the many event handlers you can use to trigger some JavaScript.

The first part of the JavaScript code "preloads" the images, so that they are available when needed (i.e. when a user hovers over the image). Without preloading the images, the second image could take a few seconds to load when the user hovers over. This would ruin the intended effect. It's usually nicer to have the image respond immediately rather than wait a second or two.

The second part of the JavaScript code is a function. This particular function swaps the images. It gets called when the user hovers over the image. How does the web page know that the user hovered over the image? It knows because it has the onmouseover event handler. This event handler calls the swapImage() function that swaps the images.

Have you met Jack's brothers?