Fade In Image Fade Out another

Hi,

I am using the following function to fade out one image and fade in another (replacement), however currently this fades out so to white before another image fade in, is it possible to fade ontop gradually so it does not fade out completely?

               
if (dataId != $('img#largeImg').attr('src').replace(/\?(.*)/, '')) {
                    $('img#largeImg').stop().animate({
                        opacity: '0'
                    }, function () {
                        $(this).attr('src', dataId + '?' + Math.floor(Math.random() * (10 * 100)));
                    }).load(function () {
                        $(this).stop().animate({
                            opacity: '1'
                        });
                    });
                }

Open in new window


Any help is appreciated.
sanjshah12Asked:
Who is Participating?
 
Julian HansenCommented:
The reason this is happening is that you are only start the fade in after the fade out has finished.

What you need to do is start the fade in of the second image at the same time as you start the fade out of the first.

I have put together a sample that demonstrates this
CSS
<style type="text/css">
.imgContainer {
  position: relative;
  width: 800px;
}
.imgContainer img {
  width: 100%;
  position: relative;
}
.imgContainer img:last-child {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
}
</style>

Open in new window

HTML
  <div class="imgContainer">
    <img src="images/background3.jpg" />
    <img src="" />
  </div>

Open in new window

jQuery
<script>
$(function() {
  var id = 3;
  // LOOP FOREVER
  setInterval(function() {
    // GET NEXT IMAGE
    var nextImage = 'images/background' + (id++ %7+ 1) + '.jpg';

    // ANIMATE VISIBLE IMAGE OUT
    $('.imgContainer img:first-child').animate({
      opacity: 0
    },1500, function() {
      // CLEAR THE INVISIBLE IMAGE
      $(this).attr('src', '');
    });
    // AT THE SAME TIME ANIMATE NEXT IMAGE IN
    $('.imgContainer img:last-child').attr({src: nextImage}).animate({
      opacity: 1
    },1500, function() {
      var parent = $(this).parent();
      // MOVE VISIBLE IMAGE TO FRONT OF QUEUE
      $(this).remove().prependTo(parent);
    });
  }, 5000);
});
</script>

Open in new window

You can see it working here
0
 
sanjshah12Author Commented:
many thanks Julian, I will test in my application and get back to you shortly.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.