Javascript Image Preloader with Image Swapping Function

In this post you will find a simple image swapping function that will work for all images that need a hover effect.

The ‘img’ argument is required of course. I can either be a reference the the image object itself (eg: swapImg(this)) or a string (eg: swapImg(‘ImageID’)) if calling the function from somewhere other than within the <img> tag. If no arguments are passed, it aborts execution. If a string is passed, we first make sure that getElementById is supported. Then we check to make sure the ID passed is valid, of not we return.

After ‘img’ has been checked and confirmed, we move on to the 2 optional arguments. The ‘find’ argument (case-sensitive) indicates the string we are looking for at the end of the image src attribute. If the string is found, we know that the image is currently in the ‘over’ state and we replace ‘find’ with ‘repl’ to return the image back to it’s normal state. On the other hand, if ‘find’ is not located, we rebuild the src attribute and insert ‘repl’ at the end of the image url (before the file extension) to activate the hover state.

function swapImg(img, find, repl) {
 if (!img) return;
 if (typeof img == 'string') {
  if (document.getElementById) {
   img = document.getElementById(img);
   if (!img) return;
  } else {
   return;
  }
 }
 if (!find) find = '-over';
 if (!repl) repl = '';
 if (img.src.search(find) >= 0) {
  img.src = img.src.replace(find, repl);
 } else {
  img.src = img.src.substr(0, img.src.length - 4) + find + img.src.substr(img.src.length - 4);
 }
}

It may look complicated, but it’s really very simple if you don’t pay attention to the argument validation and default value assignments. The last ‘if’ statement does the actual work.

Last but not least, you will likely need a javascript image preloader. Here is the code I use for that…

if (document.images) {
 imgUrls = new Array(
  'images/go-over.png',
  'images/navigation/home-over.gif',
  'images/navigation/how-over.gif',
  'images/navigation/pricing-over.gif',
  'images/navigation/faq-over.gif',
  'images/navigation/contact-over.gif',
  'images/signup-over.png'
 );
 var imgPreloaders = new Array();
 for (var i = 0; i < imgUrls.length; i++) {
  imgPreloaders[i] = new Image();
  imgPreloaders[i].src = imgUrls[i];
 }
}

Also pretty straight-forward. We make sure ‘document.images’ is supported. If it is, we create an array containing the URLs of all the images that need to be preloaded for the swapImg() function. Then we loop through that array, create the Image() objects and load the URLs into each one.

You may have noticed that I named all of my hover-state images ‘something-over.ext’. This is where the ‘find’ argument in the swapImg() function comes into play. I always append ‘-over’ to my hover images, so that is why I defaulted the function argument to that. You can always call it like…

swapImg('myImageId', 'Hover', 'Normal');

In which case it sets the img object to document.getElementById(‘myImageId’) and updates a URL like ‘images/myimageHover.png’ to become ‘images/myimageNormal.png’. Just keep in mind that the ‘find’ string must be unique and not have the chance of existing elsewhere in the image’s filename. The calls to swapImg() will have to flip the last 2 arguments for javascript’s onmouseover and onmouseout events as shown below.

Example (myimageNormal.png & myimageHover.png):

<img alt="" src="images/myimageNormal.png" onmouseover="swapImg(this,'Normal','Hover')" onmouseout="swapImg(this,'Hover','Normal')" />

Here are some examples of how I have recently used the function on a client’s project.

Form Image (acts as a submit button):

<input type="image" src="images/go.png" alt="Go!" onmouseover="swapImg(this)" onmouseout="swapImg(this)" />

Navigation Bar (can be used anywhere on the page):

<a href="#home" onmouseover="swapImg('navHome')" onmouseout="swapImg('navHome')">
   <img id="navHome" alt="Home" src="images/navigation/home.gif" />
</a>

That’s all there is to it 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *