Contact Yart for a relaxed conversation
Your Name * Message *
Your Email *  
Your Phone   
Our Phone:        03 8685 8718 (within Australia)
61 3 8685 8718 (outside Australia)
Contact Yart

Melbourne Content Management and Flash developers

 

for designers, agencies and your website

Resources / jQuery / jQuery - Auto replace image on hover
jQuery: Auto replace image on hover

Sample: (hover over the heart)

The HTML for the above image is simply:
<img class="imgHoverable" src="images/heart.gif" />
But there is some jQuery code behind it that does the image-replacing automatically, for all images with class "imgHoverable".

How to do it

  1. The hover image filename must be the same as the default one, with "_hover" added at the end.
    eg. submit.png and submit_hover.png
    Both images must be put in the same folder.
  2. Put this code in the <head> tag.
    (Change the path to your jquery.js if different)
    <script type="text/javascript" src="Scripts/jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
       // Change the image of hoverable images
       $(".imgHoverable").hover( function() {
           var hoverImg = HoverImgOf($(this).attr("src"));
           $(this).attr("src", hoverImg);
         }, function() {
           var normalImg = NormalImgOf($(this).attr("src"));
           $(this).attr("src", normalImg);
         }
       );
    });

    function HoverImgOf(filename)
    {
       var re = new RegExp("(.+)\\.(gif|png|jpg)", "g");
       return filename.replace(re, "$1_hover.$2");
    }
    function NormalImgOf(filename)
    {
       var re = new RegExp("(.+)_hover\\.(gif|png|jpg)", "g");
       return filename.replace(re, "$1.$2");
    }
    </script>
  3. Add the class "imgHoverable" to the image.
    eg.
    <img class="imgHoverable" src="images/submit.png"/>

That's it. Now when you hover over any "imgHoverable" image, jQuery will automatically change the src of the <img>.
Eg. from images/submit.png to images/submit_hover.png

The latest at Yart
Search: