egr103 egr103 - 26 days ago 6
jQuery Question

jQuery carousel - any number of images

I have a Flickity carousel of images that, when you click an image/slide, opens a modal window to show a zoomed in version of said image. Within that modal I have a left and right buttons to scroll through all zoomed in images.

My problem is my code breaks if I have any more or less than 3 images in the slider. I need to convert it so that it will not break no matter how many images I have, whether its 1, 4, 2 or 8 etc. How do I do this?

My JS below has been reduced to show just the relevant bits. I also have a function for a right button too. See jsFiddle for current situation: https://jsfiddle.net/293sh54n/6/

JS

var activeDivimg;
$( ".product--slider .slide" ).each(function( index ) {
// Show the modal window
$('#product-slider-flickity img').click(function(){
activeDivimg = parseInt($(this).parent().index());
console.log(activeDivimg)
$("#imageshow").html('<img src="'+$(this).attr('src')+'"/>');
$(".p-image-zoom").addClass("md-show");
});
});
// Zoomed in controls - Scroll left button
$('.left').click(function(){
if(activeDivimg < 1 ){
activeDivimg = 2
}else{
console.log('kundi'+activeDivimg)
activeDivimg = activeDivimg - 1
}
console.log('left'+activeDivimg)
$("#imageshow").html('<img src="'+$('.slide').eq(activeDivimg).find('img').attr('src')+'"/>');
console.log(activeDivimg+"asd")
});

Answer

First of all you should get images count. After this in left click you use activeDivimg = imagesCount - 1; instead of activeDivimg = 2; Same thing right click. fiddle

var imageCount = $('.slide').length;
var activeDivimg;
$( ".product--slider .slide" ).each(function( index ) {
  // Show the modal window
  $('#product-slider-flickity img').click(function(){
    activeDivimg = parseInt($(this).parent().index());
    console.log(activeDivimg)
    $("#imageshow").html('<img src="'+$(this).attr('src')+'"/>');
    $(".p-image-zoom").addClass("md-show");
  });
});
// Zoomed in controls - Scroll left button
$('.left').click(function(){
   if(activeDivimg < 1 ){
    activeDivimg = imagesCount - 1;
   }else{
      console.log('kundi'+activeDivimg)
      activeDivimg = activeDivimg - 1
   }
   console.log('left'+activeDivimg)
   $("#imageshow").html('<img src="'+$('.slide').eq(activeDivimg).find('img').attr('src')+'"/>');
    console.log(activeDivimg+"asd")
});