Smooth image fade out, change src, and fade in with jquery
Asked Answered
S

1

12

I am trying to do the following:

On link click:

1.) fade out an img

2.) change the src of the now hidden image

3.) when the img with the new src finishes loading, fade in

Minimally, I'd like to see a smooth fade out of one image and a fade in of another (within the same img tag by changing the src)

Eventually I'd like to:

1.) fade out an img

2.) show a animated gif "loading image"

3.) change the src of the now hidden image

4.) hide the animated gif "loading image"

5.) when the img with the new src finishes loading, fade in

Thanks.

This is what I tried so far. It seems to do a couple flashes but only after the src changes (prior to the fade out). Strange behavior.

$("#Image").fadeOut();
$("#Image").attr("src", NEW_IMAGE_SRC);
$("#Image").fadeIn();

#Image is an IMG tag

Synchronize answered 31/3, 2012 at 21:39 Comment(1)
What have you tried so far? Where did you get stuck? Also, consider using sprites.Negrophobe
A
36

Try this:

$('.click').click(function() {
   $('img.class').fadeOut(300, function(){
      $(this).attr('src','new_src.png').bind('onreadystatechange load', function(){
         if (this.complete) $(this).fadeIn(300);
      });
   });
});
Appointed answered 31/3, 2012 at 21:44 Comment(1)
Awesome answer, this proved to be much smoother than chaining fadeOut and fadeInIlliteracy

© 2022 - 2024 — McMap. All rights reserved.