Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Hover image change animation

Tags:

jquery

I have an IMG tag with a grayscale image. I hooked up a Hover() event in order to change the "src" to a color image on hover, and back to grayscale on mouse-out.

This works just fine, however the change is abrupt. I'd like to add a slight fadeIn() to the effect so that the color appears to fadein and fadeout. I wrote the following which I thought would work, but doesn't. (The image changes, but there is no fade or delay to the effect). What am I doing wrong?

            $("#showForm").hover(
              function () {
                $(this).fadeIn('slow', function(){
                    $(this).attr("src", 'images/AddButtonSmall.gif');
                });
              }, 
              function () {
                $(this).fadeIn('slow', function(){
                    $(this).attr("src", 'images/AddButtonSmallGray.gif');
                });
              }
            );
like image 764
Todd Davis Avatar asked Apr 06 '12 04:04

Todd Davis


1 Answers

Here are a couple solutions. Your code doesn't work because you are setting the source which changes the image immediately. It's probably easier just to load both images, overlay them with CSS and then fade the color one in out when the parent container is moused over. Alternatively you could cross fade them

css

.fader { display: inline-block; }
.fader img:last-child {
    position: absolute;
    top: 0; 
    left: 0;
    display: none;
}​

html

<div class="fader">
    <img src="http://placehold.it/300x300/000fff" />
    <img src="http://placehold.it/300x300/fff000" />
</div>​

fade in on mouseover

http://jsfiddle.net/Xm2Be/3/

$('.fader').hover(function() {
    $(this).find("img:last").fadeToggle();
});​

cross fade

http://jsfiddle.net/Xm2Be/2/

$('.fader').hover(function() {
    $(this).find("img").fadeToggle();
});​
like image 179
mrtsherman Avatar answered Oct 14 '22 22:10

mrtsherman