Add transition while changing img src with javascript

ernerock picture ernerock · May 10, 2014 · Viewed 37.6k times · Source

I have an img tag that I want to change the src when hover and it all works but i would like to add some transition so it doesn't look so rough but since it's an img src i cant target it with css.

http://jsfiddle.net/Ne5zw/1/

html

<img id="bg" src="img/img1.jpg">
<div onmouseover="imgChange('img/img2.jpg'); "onmouseout="imgChange('img/img1.jpg');">

js

function imgChange(im){
document.getElementById('bg').src=(im);
}

Answer

Mister Epic picture Mister Epic · May 10, 2014

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/