jfox
jfox

Reputation: 898

jQuery counter + each reset

I'm using the code below to move images in a pair of sliders, but the first slider is jumping an extra step before resetting. slider 1 = 5 images, slider 2 = 6 images

function summarySlider(count) {
  var itemWidth = '20.2';
  var itemList = $('.summary-item-list');
  $(itemList).css('transform', 'translateX(-'+ (itemWidth * count) +'%)');
}
$(window).on("load", function () {
  $('.summary-v2-block').each(function(index){
    var count = 0;
    var limit = $(this).find('.summary-item').length;
    setInterval(function() {
      if (count === limit) {
        count = 0;
      }
      console.log(index, limit,  count);
      summarySlider(count);
      count++;
    }, 2500);
  });
});

I think what is going on is that index 0 is actually the second slider, and index 1 is the first slider. It's counting indexes backwards? How can I make index 0 the first slider?

This is the console output (index, limit, count)

0 5 0

1 6 0

0 5 1

1 6 1

0 5 2

1 6 2

0 5 3

1 6 3

0 5 4

1 6 4

0 5 0

1 6 5

0 5 1

1 6 0

Upvotes: 0

Views: 578

Answers (1)

charlietfl
charlietfl

Reputation: 171669

The issue isn't the timing but rather that your summarySlider function is looking for and manipulating elements that exist in both sliders.

You could pass in another argument for the parent slider element and use find() to make it instance specific

function summarySlider($slider, count) {
  var itemWidth = '20.2';
  var itemList = $slider.find('.summary-item-list');
  $(itemList).css('transform', 'translateX(-'+ (itemWidth * count) +'%)');
}
$(window).on("load", function () {
  $('.summary-v2-block').each(function(index){
    var count = 0;

    var $slider=$(this);// to pass to `summarySlider()`

    var limit = $(this).find('.summary-item').length;
    setInterval(function() {
      if (count === limit) {
        count = 0;
      }
      console.log(index, limit,  count);
      summarySlider($slider, count);
      count++;
    }, 2500);
  });
});

Upvotes: 1

Related Questions