Friday, 29 January 2010

jQuery image roll-overs

On the site I am currently working on I needed to implement hover/roll-over states for a number of image tags. Other elements in the site use the CSS based x:hover{background:y} approach, but that was not an appropriate solution for these instances - background images were not going to used, so I came up with a nice jQuery based solution that keeps my page-source pretty uncluttered too.

I added a class value of "hover" to the image tags I wanted to exhibit this behaviour. The replacement images all had the suffix _hover added (e.g. theimage_hover.png )

<img src="/images/theimage.png" class="hover">

Then in my main javascript file I added this little snippet:

function imghover_on(img){if(img.src.indexOf('_hover.')==-1){img.src=img.src.substr(0,img.src.length-4)+'_hover'+img.src.substr(img.src.length-4)}}

function imghover_off(img){img.src = img.src.replace('_hover.','.');}

jQuery("img.hover").mouseenter(function(e){ imghover_on(this);});
jQuery("img.hover").mouseleave(function(e){ imghover_off(this);});

This code declares two functions which add or remove the "_hover" suffix to the image tag's source, while not needing to know if the image is .png .gif or .jpg.

The jQuery statement waits for the page to load and then finds all img tags in the document with the hover class set and binds the function calls to the mouseenter and mouseleave. This saves me from having to add these events to every single image tag manually like this:

<img src="/images/theimage.png" onmouseover="imghover_on(this);" onmouseout="imghover_off(this)">


  • I used mouseenter/mouseleave as they fire a lot less than mouseover/mouseout (see: )
  • It's not infallable, a .jpeg file extension would fail, but it's working nicely for first cut.

No comments:

Post a Comment