1

I am trying to change the src of an existing image with a series of other images. I have got this working but the transition is terrible and not smooth at all. I guess this is because it abruptly loads the new image AFTER the initial one is faded out rather than at the same time.

Is there any clever way to make this transition completely smooth?

var images = new Array ('image1.jpg', 'image2.jpg', 'image3.jpg');
var index = 1;

function rotateImage()
{
  $('.Parallax-host').children(':first-child').find('.Index-page-image img').fadeTo(1000,0.30, function() 
{
$(this).attr('src', images[index]);

$(this).fadeTo(500,1, function() 
{
  if (index == images.length-1)
  {
    index = 0;
  }
  else
  {
    index++;
  }
});
});
} 

$(document).ready(function()
{
 setInterval (rotateImage, 5000);
});

I dont have access to the markup here so it needs to be a jquery only solution.

j00m
  • 491
  • 5
  • 20

1 Answers1

0

here's something to get you started.

const images = ["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQnY5_NI7cYhnEqnNWcyX29B6x71CmUp1Xs_uFCkIrWEzuBhXf","https://pbs.twimg.com/profile_images/562466745340817408/_nIu8KHX.jpeg","https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350"];
let curImage = 0;
function rotateImage(){
  let next = document.createElement('img');
  next.onload = function(e){//wait for the image to load
    document.getElementById('img_container').insertBefore(next, document.querySelector("#img_container img"));//insert new image before the previous (for stacking order)
    $('#img_container img').eq(1).fadeOut(1500, function(){
      $(this).detach();//remove the faded out img
    });
  };
  next.src = images[curImage];
  curImage = (curImage + 1) % images.length;
}
setInterval(rotateImage, 5000);
#img_container{
  width:300px;
  height:300px;
  position:relative;
  overflow:hidden;
}
#img_container img{
  position:absolute;
  top:0;
  left:0;
  bottom:0;
  right:0;
  min-width:100%;
  min-height:100%;
  margin:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='img_container'>
  <img src="https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350" />
</div>
dgeare
  • 2,618
  • 5
  • 18
  • 28