Reputation: 3073
I am trying to use next and prev arrows to switch images and I use next() to fade next image, but when there are no images left it obviously won't recycle from the first image. How to make this code work and let the next button go to first image after reaching the end of images element with that class.
My code:
$('.nextImage').live('click',function(){
$('.main-image .zoom:visible').fadeOut(800);
$('.main-image .zoom:visible').next().fadeIn(800);
});
Upvotes: 0
Views: 774
Reputation: 92893
Just test if there is a next element, and if not, return to the beginning.
$('.nextImage').on('click',function(){ // .live() is deprecated
var $img = $('.main-image .zoom:visible').last(), // just want one
$next = $img.next();
if (0==$next.length) {
$next = $img.siblings().first();
}
$img.fadeOut(800);
$next.fadeIn(800);
});
Upvotes: 2