Search code examples
jqueryimagefade

jQuery fading two images without white


I would like to fade image without white transfer between them.

HTML:

<div class="image">
  <span><img src="1.jpg"></span>
</div>

jQuery:

$('.image > span > img').fadeOut(1000, function() {
  $('.image > span > img').attr('src', images[i]);
  $(this).fadeIn(1000);
});

This works, but there is white fade between changing. Images array contains image sources. I found this http://jsfiddle.net/byB6L/ but I can not update my code to work with that.


Solution

  • This is because your using the same image on the animation end callback.

    My suggestion: use position: relative; on the class="image" container, put the image element as position:absolute;, now after you are fading the image out insert a new image into the container and fade it in and remove the first image.

    Example:

    Html:

    <div class="image">
      <span><img src="1.jpg"></span>
    </div>
    

    Css:

    <style type="text/css">
        .image{position:relative;}
        .image span img{position:absolute;top:0;left:0;}
    </style>
    

    JavaScript:

    <script type="text/javascript">
        $('.image > span > img').fadeOut(1000);
        var $image = $('<img alt="" src="YOUR NEW IMAGE_PATH" style="opacity:0;" />');
        $('.image > span').append($image);
        $image.fadeIn(1000, function(){
            $('.image > span > img').first().remove();
        });
    </script>