Thursday, April 17, 2008

jQuery Quick Tip: Rollover images with jQuery

Update: Demo page created

There are several sites that show you how to create rollover images with jQuery (just search Google, Ask, A9, Yahoo etc) for "rollover image jquery"), but they do sometimes have more code than needed (like using $(this).attr("src") instead of this.src for determining the image source. Here is another method that does not use jQuery unnecessarily (which may be faster if there are lots of images).

Create two images, for the 'off' state (when mouse is not over it) and the 'on' state (on mouse over). Name them button_off.gif and button_on.jpg (the button bit can be anything, as can the extension (.gif) - the important bit is the _off and _on suffix.

HTML code:

<a id="mylink" href="/go/somewhere/"><img src="/images/button_off.gif" alt="" title="" border="0" width="100" height="30" /></a>

Then in your $(document).ready:

$("#mylink img").hover(
  this.src = this.src.replace("_off","_on");
  this.src = this.src.replace("_on","_off");

Due to its generic nature, it can be applied to multiple images, e.g. those with a class .rollover set $("img.rollover").hover...


Anonymous said...

This is Nice...brief & simple
Well done

Have I had a busy day...BECAUSE I cannot see an example.
Tom Morris

Sam said...

Didn't manage to create one at the time of posting, but have put a demo page up now.

Anonymous said...

Does this only work with one linked image per page?

Sam said...

You can do it with multiple images as it does it in a generic way - as shown on the demo page.

Anonymous said...

You can also try jquery swap image, e.g.

Justin said...

Just came across this on how to glam up rollovers with JQuery-

I found it helpful, but you have to be familiar with at least the basics of JQuery. Thanks for this post, it was nice and simple.