Programming Books

AJAX

Shorten your javascript image hover scripts with a neat jQuery plugin (CANVASSWAP)

So what is CANVASSWAP?

A jQuery plugin to induce an image swap on hover. Although this plugin 
does it's job of swapping out images extremely well , that's not what
it's main intention is. What canvasSwap sets out to do is not only provide 
a great image swap utility, but it also allows swapping
transparent PNG images in IE 6! (with the help of a PNG transparency script)

(linewraps are mark with »)

function toggleImage(a){ 
  if(document.getElementById(a).src.indexOf » 
("1.png")>-1){document.getElementById(a).src=document.getElementBy » 
Id(a).src.replace("1.png","2.png")}};
 
This code switches one image with another when toggled. 
We could shorten this code to perform much faster by using regular 
javascript like this
 
Note that document.getElementById(a).src is repeated three times, 
which is almost exactly the same as the original (with the exception 
of the variable name).  
 
function toggleImage(id){
  var image = document.getElementById(id);
   if (image.src.indexof('1.png')>-1) { 
      image.src=image.src.replace('1.png','2.png');
   }
} 
 
We've just saved about 150 bytes by illuminating the use of a property 
multiple time. and increase execution of our code.
 
But we can save even more time an space by using the jQuery CANVASSWAP method. 
Like so...
 
Example: To induce an image swap on images with the
class of 'myswap', the image to swap having a suffix of '_hover', 
and IE 6 PNG support enabled.
 
$(document).ready(function(){
   $.fn.canvasSwap.defaults.suffix = '_hover';
   $.fn.canvasSwap.defaults.ie6_support = true;
   $('img.myswap').canvasSwap();
});

<img src="myimage.png" alt="myimage" class="myswap" width="300" height="225"/>
 
 This code is also hosted on Google!