I am trying to achieve a smooth transition when changing the image source on click using previous/next buttons. I want the image to fade out, then change source and fade back in, but I'm having trouble getting it to work seamlessly. I attempted to use .delay()
between the fading animations and source change, but the source change is still happening before the fading completes. I also tried using .stop()
, but that only stops the currently running animation and doesn't affect attribute changes.
var images = ['http://i.imgur.com/U82gG8H.jpg', 'http://i.imgur.com/kVy4G4R.jpg', 'http://i.imgur.com/BtMikrd.jpg'];
var count = 0;
$('.next').on('click', function() {
if (count !== images.length-1) {
count++;
$('.product_image img').fadeTo(300, 0).delay(600).attr('src', '').attr('src', images[count]).fadeTo(300, 1);
}
});
$('.previous').on('click', function() {
if (count !== 0) {
count--;
$('.product_image img').fadeTo(300, 0).delay(400).attr('src', '').attr('src', images[count]).fadeTo(300, 1);
}
});
.navigation {
display: block;
}
.navigation .previous,
.navigation .next {
width: 30px;
height: 30px;
line-height: 30px;
text-align: center;
background: #ddd;
color: #fff;
display: inline-block;
margin-right: 20px;
cursor: pointer;
}
.navigation .next {
margin-right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="product_image">
<img src="http://i.imgur.com/U82gG8H.jpg" />
</div>
<div class="navigation">
<div class="previous"><</div>
<div class="next">></div>
</div>
Any assistance would be greatly appreciated.