jQuery Mouseover for Inline Images
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:
- Upload the two image states coffee-OFF.jpg and coffee-OVER.jpg into the same folder (case sensitive)
- 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/