Slowly change/fade/animate an image changing with JQuery

zafrani picture zafrani · May 7, 2012 · Viewed 40.3k times · Source

This is my img, <img src="one.png" id="one" onMouseOver="animateThis(this)">

I want to slowly change this image src to "oneHovered.png" when the user hovers over using jQuery. Which jQuery method is best to do this? A lot of examples I see want me to change the CSS background. Is there anything to alter the src attribute directly?

Answer

jmort253 picture jmort253 · May 7, 2012

You could start by first fading out the image, controlling the duration of the fadeout using the first optional parameter. After the fade out is complete, the anonymous callback will fire, and the source of the image is replaced with the new one. Afterwards, we fade in the image using another duration value, measured in milliseconds:

Original HTML:

<img src="one.png" id="one" />

JavaScript:

$('#one').hover(function() {

    // increase the 500 to larger values to lengthen the duration of the fadeout 
       // and/or fadein
    $('#one').fadeOut(500, function() {
        $('#one').attr("src","/newImage.png");
        $('#one').fadeIn(500);
    });

});

Finally, using jQuery, it's much, much easier to bind JavaScript events dynamically, without using any JavaScript attributes on the HTML itself. I modified the original img tag so that it just has the src and id attributes.

The jQuery hover event will ensure that the function fires when the user hovers over the image with the mouse.

For more reading, also see jQuery fadeOut and jQuery fadeIn.

Possible problems with image load times:

If it's the first time a user has hovered over an image and making a request for it, there may be a slight glitch in the actual fadeIn, since there will be latency from the server while it's requesting newImage.png. A workaround for this is to preload this image. There are several resources on StackOverflow on preloading images.