jQuery Mouseover for Inline Images

January 13, 2010 · Posted in Web Stuff 

I was hoping to find a WordPress plugin for creating a mouseover or hover effect on an image that is not a hyperlink, but none is available. So what I wanted is for my client to be able to post an image on a page and in a simple way, swap the image onmouseover.

Here is what I did, when inserting an image into the web page I give it the class “swapper” and ame the mouseout or default state of the image -OFF:

<img class="swapper" src="http://xyz.com/coffee-OFF.jpg" />

Then the jQuery function to do the swapping:
<script>
$(document).ready(function(){
// do this on hover for images with the class swapper
$("img.swapper").hover(function() {
//Get the src attribute of the default image
rollSRC = $(this).attr("src");
//Replace -OFF with -OVER for the rollover version
rollOVER = rollSRC.replace('-OFF', '-OVER');
$(this).attr("src", rollOVER );
}, function() {
//revert to the original image
$(this).attr("src", rollSRC );
});
});
</script>

If you are using this on WordPress change all the $ signs to jQuery (eg jQuery(document).ready(function()...)

Now I should be able to explain to the client that they need to:

  1. Upload the two image states coffee-OFF.jpg and coffee-OVER.jpg into the same folder (case sensitive)
  2. Insert the default image with the class=”swapper”

So Simple how can it go wrong!

Of course I did not come up with this entirely on my own, the following articles all helped me:

http://www.atlantajones.com/web-dev/even-easier-jquery-rollovers/

http://bavotasan.com/tutorials/a-simple-mouseover-hover-effect-with-jquery/

http://www.frodesigns.com/2009/07/wordpress-jquery-image-rollovers/

  • Google Bookmarks
  • Digg
  • del.icio.us
  • Twitter
  • Technorati
  • Facebook
  • Reddit
  • Mixx
  • email
  • RSS

Comments

Leave a Reply