Path // www.yourhtmlsource.comImages → IMAGE ROLLOVERS

Image Rollovers


The classic image flip script is one of the most popular pieces of JavaScript on the web. Using this, you can make an image change to a different image on response to the user placing their mouse in a certain position. This is achieved by loading a new image in the original’s place. When used correctly, they can really add a bit of life to a page. You don't need to have any JavaScript experience to use these scripts; it's a simple copy ‘n’ paste job.

Clock This page was last updated on 2012-08-21



The Image Flip

Let’s get into the swing of things with an example — pass your mouse over the image below.

JavaScript image rollover example

This script is easy to configure, only requiring that you put some words in the right places and name your images correctly. To get the effect working, you first need two images. They should have the same dimensions (height and width), and should reside in the same directory. Give them descriptive names, and save the rolled-over version with a 2 at the end of the filename (eg: image2.gif). This is important. My two images in the flip to the left are called smirk1.gif and smirk2.gif

Once you have assembled your images, place this JavaScript onto your page. You should put it in the <head> of the document, so that it is already working before it has a chance to be called.

<script type="text/javascript">
var revert = new Array();
var inames = new Array('smirk');

// Preload
if (document.images) {
  var flipped = new Array();
  for(i=0; i< inames.length; i++) {
    flipped[i] = new Image();
    flipped[i].src = "media/"+inames[i]+"2.gif";
  }
}

function over(num) {
  if(document.images) {
    revert[num] = document.images[inames[num]].src;
    document.images[inames[num]].src = flipped[num].src;
  }
}
function out(num) {
  if(document.images) document.images[inames[num]].src = revert[num];
}
</script>

This intimidating-looking chunk of code will be able to take care of any and all rollovers you want to set up on the page. Those of you who have frequented the JavaScript tutorials should be able to make some sort of guess at what’s happening here, but for everyone’s benefit, here’s the run-down.

Break it Down One Time

First we define some variables. The revert array will be used a little later on to save the filename of the image we want to return to when the effect ends. The inames array is used to store the names of all the images that we want to flip — entries should be encased in single-quotes and separated by commas.

Next comes the preload code, which automatically loads the images that are going to be called by the script. These need to be ready to go when the script calls them, as otherwise there’ll be a downloading pause before the image flips. We simply go through the inames array and, for each image, load its flipped version in the background. These images are stored in the browser’s cache, ready to leap into the fray. I keep my images in the folder media/ — you should change this to whatever your folder is named.

sourcetip: Your images, especially the one that appears during the flip, will have to load very quickly if the effect is going to be a success. Even with the built-in pre-load, you must still keep them small by optimising them down.

Finally we have the two functions that will do all the magic, over and out. Each image object has the modifiable property src, the image’s filename. When the user places their mouse on the image, over is called. Once the support detection is done, it saves the file’s current src value into a slot in revert. It then changes the src value to the preloaded version we have ready. The images will switch.

Once the user then moves their mouse back off the image, we want it to change back to its original value, which we cunningly saved for this purpose into the revert variable. So, the out function merely reassigns the image’s src value to this filename, and the image returns to its initial state. Ace.

Inserting the Images

Right, so that’s the script sorted out, now we just need to add the images. This is done like any other image, but with some extra JS attributes thrown in:

<img src="media/smirk1.gif" name="smirk" onMouseOver="over(0)" onMouseOut="out(0)">

This HTML creates the image. The script will then wait for the user to trigger it. The onMouseOver event handler ‘listens’ for certain user actions; in this case their mouse passing over the image. When this happens it fires the over function, and sends the image’s number along with it. It’s the first rollover image on the page so it sends a 0. The second image would send a 1 etc. Always remember, the first object in an array is numbered with a zero.

When the user’s mouse moves away from the image again, onMouseOut notices and fires out, again adding in the image’s number so the function knows which image it has to work on.

Filenames

The name attribute we add to our images should be exactly the same as the names we gave the image in the inames array in the script. This is used to construct the rolled-over image’s filename. If we call our first image smirk, as I have done, the script decides that the corresponding rolled-over filename will be media/smirk2.gif. The initial image can be called anything you want, but it would be a good idea to name it similarly to the second, ending with a 1.

Multiple Rollovers

Expanding the script’s usefulness to many rollovers on the same page is easy — you simply add a new entry to the inames array and then send a different number with the functions. So, to add a second rollover, one line in the script will need to be modified:

var inames = new Array('smirk', 'smile');

The image code will be similar:

<img src="media/smile1.gif" name="smile" onMouseOver="over(1)" onMouseOut="out(1)">

That’s it. Each new rollover image just needs a new entry in inames and the correct number to be sent with the functions.

Changing Multiple Images Together

You can even set it up so that two or more images change at a time. This is achieved easily too — by simply executing the over and out functions repeatedly for each event. Because each image has a unique index in the inames array, they will not interfere with each other. Mousing over the following link would change the first two rollover images on the page simultaneously, and then switch them both back on MouseOut — also demonstrating how the image itself does not have to be the triggering element.

<a href="index.html" onMouseOver="over(0), over(1)" onMouseOut="out(0), out(1)">Flip off</a>

In a similar fashion, you can also get the image to change onClick, though this is rarely used as the event doesn’t last very long.