Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM

A fairly common question on Yahoo! Answers centers on thumbnail image galleries, where a “master” image changes whenever you mouse over various thumbnails. Such as this one:

Mouseover thumbnail in one frame changes pic in different frame in Javascript-Need Help!?

{code snipped}

Good: image displayed in content frame
bad: image does not update to a new image (x var)
bad: writeContent() excutes repeatedly stacking images(mouseover)

Some time ago I had discussed swapping a “master” image’s source when someone clicked on a thumbnail, and had directed mouseover questions to that blog entry. But this gives me a chance to answer the mouseover question directly, and to add a bonus feature: pre-loaded images, so the image swaps occur almost instantaneously.

I’ll also provide two examples: One that leaves the new image until a different thumbnail is moused over, and another that restores the original image any time you mouseout of a thumbnail.

As always, the code and the sample images are available for download at the end of this article.

Step 1: The HTML

We begin with some simple HTML: Two DIVs that will hold the main image and the thumbnails.

Each of the thumbnails will have an onmouseover event that calls our image-swapping program. And our BODY tag will call a function named preloadImages, which will load the swap images at the same time the page itself is loaded. (You can, of course, exclude this step, but there will be a delay between the time you mouse over the thumbnail and the image loads and displays if you don’t preload.)

<body onload="preloadImages()">

<div id="image">
	<img id="theImage" src="images/marisa_miller6.jpg" alt="Marisa Miller" />
</div>

<div id="thumbs">
	<img src="images/marisa_miller1_tn.jpg" alt="Marisa Miller 1" onmouseover="swapImage(0)" />
	<img src="images/marisa_miller2_tn.jpg" alt="Marisa Miller 2" onmouseover="swapImage(1)" />
	<img src="images/marisa_miller3_tn.jpg" alt="Marisa Miller 3" onmouseover="swapImage(2)" />
	<img src="images/marisa_miller4_tn.jpg" alt="Marissa Miller 4" onmouseover="swapImage(3)" />
	<img src="images/marisa_miller5_tn.jpg" alt="Marissa Miller 5" onmouseover="swapImage(4)" />
	<br />
	<em>[ mouse over the thumbnails to see a larger picture ]</em>
</div>

Step 2: Set Some Global JavaScript Variables

Because we have a couple of functions that are going to share both the images we intend to display and the path to those images, it makes sense to set them as global variables.

Each large image we intend to display will become a cell in a JavaScript array. And we’ll set a simple string variable that provides the relative path to the directory those images are in. (Yes, this script assumes all the images you intend to have in your gallery will be in the same directory.)

var imgArray = new Array(
	'marisa_miller1.jpg',
	'marisa_miller2.jpg',
	'marisa_miller3.jpg',
	'marisa_miller4.jpg',
	'marisa_miller5.jpg',
	'marisa_miller6.jpg'
);

var imgPath = "images/";

Step 3: The preloadImages() Script

Update, 19 December 2013: This method of preloading images is harebrained nonsense. See Preloading Images With JavaScript for the right way to preload images. (I’m retaining this copy for search engine visibility. Blame Google.)

Again, this step is optional, but you’ll find the performance of your gallery improves significantly if you preload the images that will appear on mouseover.

To preload images, we simply iterate through the entire array of large images, creating new JavaScript Image objects for each and setting their src attributes to be one of the images in the array. By doing that, we make the visitor’s Web browser load into its cache each of the images we will display. That, again, means they will appear almost instantly on mouseover.

function preloadImages() {
	for(var i = 0; i < imgArray.length; i++) {
		var tmpImg = new Image;
		tmpImg.src = imgPath + imgArray[i];
	}
}

Step 4: The swapImage() Function

Swapping images couldn’t be easier.

Each onmouseover event sends to the function one of the indexes of our image array (where Image 1 is Index 0; Image 2 is Index 1, etc.). We simply get the “master” image via getElementById(), then assign its src attribute to be a combination of the path to the image directory, and the appropriate index of our images array.

function swapImage(imgID) {
	var theImage = document.getElementById('theImage');
	var newImg;
	newImg = imgArray[imgID];
	theImage.src = imgPath + newImg;
}

And believe it or not, it’s as simple as that. You can see the script in action here:

http://www.dougv.com/demo/js_larger_image_tn_mouseover/

Step 5: Restoring The Original Image On MouseOut

Sometimes, you’ll want to be able to return to the original, “master” image when someone moves his mouse off one of the gallery icons. That’s easily accomplished by simply adding an onmouseout event to each thumbnail. That event will always call the default image’s array index as its argument; for simplity’s sake, it makes sense to have that as either the first item in the array (Index 0) or, as I have done here, the last.

<div id="thumbs">
	<img src="images/marisa_miller1_tn.jpg" alt="Marisa Miller 1" onmouseover="swapImage(0)" onmouseout="swapImage(5)" />
	<img src="images/marisa_miller2_tn.jpg" alt="Marisa Miller 2" onmouseover="swapImage(1)" onmouseout="swapImage(5)" />
	<img src="images/marisa_miller3_tn.jpg" alt="Marisa Miller 3" onmouseover="swapImage(2)" onmouseout="swapImage(5)" />
	<img src="images/marisa_miller4_tn.jpg" alt="Marissa Miller 4" onmouseover="swapImage(3)" onmouseout="swapImage(5)" />
	<img src="images/marisa_miller5_tn.jpg" alt="Marissa Miller 5" onmouseover="swapImage(4)" onmouseout="swapImage(5)" />
	<br />
	<em>[ mouse over the thumbnails to see a larger picture ]</em>
</div>

You can see that modification in action here:

http://www.dougv.com/demo/js_larger_image_tn_mouseover/restore.html

You can download the full source code and sample images here: Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM demo code

I distribute code under the GNU GPL. See Copyright & Attribution for details.

8 thoughts on “Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM

  1. Pingback: dougv.com | The Web home of Doug Vanderweide » Blog Archive » Swapping An Image From A Non-Animated GIF To An Animated GIF Via JavaScript / DOM

  2. Pingback: dougv.com | The Web home of Doug Vanderweide » Blog Archive » An Image-Based ‘Checkbox’ Via JavaScript / DOM

  3. Clifford

    I tried to use the information from this page to achieve the same goal but I keep getting an object expected error in IE 8 and it just won’t roll in other browsers, what have I done wrong?

  4. Doug Vanderweide

    Clifford: Without seeing your code, I can’t directly answer your question. Follow up with a link to a sample of the problem you are having and I can directly answer the question.

    Generally speaking, if you are getting “object expected” errors, you aren’t properly invoking the swapImage() function in the image’s onmouseover or onmouseout event (or, possibly, both). Remember, the argument to swapImage() must be the index position of the image in the array of images you are using.

    It is also possible you have forgotten to include the array or changed its scope to no longer be global.

Leave a Reply