Add transition while changing img src with javascript

You want a crossfade. Basically you need to position both images on top of each other, and set one’s opacity to 0 so that it will be hidden:

<div id="container">
    <img class="hidden image1" src="http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg">

    <img class="image2" src="http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg" />
</div>

CSS:

.hidden{
 opacity:0;   
}

img{
    position:absolute;
    opacity:1;
    transition:opacity 0.5s linear;
}

With a transition set for opacity on the images, all we need to do is trigger it with this script:

$(function(){
    debugger;
    $(document).on('mouseenter', '#hoverMe', function(){
        $('img').toggleClass('hidden');
    });
});

http://jsfiddle.net/Ne5zw/12/

Leave a Comment