0

So using jQuery I change the source of an image using img.attr('src', 'img.png').

This just change the source and updates the image in a very static way, without doing any animation like fading.

How would I animate this change of image?

Shuzheng
  • 11,288
  • 20
  • 88
  • 186
  • Are you replacing the src of an image or is a newly created image element without a src? – Vincent Orback Feb 07 '16 at 12:13
  • 1
    Duplicate: [jQuery Change Image src with Fade Effect](http://stackoverflow.com/questions/5979418/jquery-change-image-src-with-fade-effect) – Yogi Feb 07 '16 at 12:24

2 Answers2

3

Hope this will help. Saw this solution somewhere when I faced this issue.

$("#link").click(function() {
    $("#image").fadeOut(1000, function() {
        $("#image").attr("src",$("#link").attr("href"));
    }).fadeIn(1000);
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image" src="http://www.google.com/logos/2011/trevithick11-hp.jpg"/>
<a id="link" href="http://www.google.com/logos/2011/mothersday11-hp.jpg">Change picture</a>
zakaiter
  • 439
  • 3
  • 11
2

Fade out the imgage and, while image is invisible, change it's source:

$('#myImg').fadeOut().queue(function() {
   var img = $(this);
   img.attr('src', newSrc);
   img.fadeIn();
   img.dequeue();
});
kapantzak
  • 11,610
  • 4
  • 39
  • 61