D_S D_S - 22 days ago 7
HTML Question

Creating a carousel effect with jquery - Loop returning only the last value in array [SOLVED]

I'm trying to create a carousel effect, but my loop is only returning the last value inside the array. I would like to iterate through each item after a specific time. Here is a codepen with the code.

Any help will be appreciated. Thanks..



$(function() {
//var timer = 3000;

var $items = $('img', '.container');
var currentIdx = 0;

var cycleItems = function() {
console.log('Running from cycleItems');
var item = [];

for (let i = 0; i < $items.length; i++) {
var item = $items[i];

setTimeout(function() {
console.log('We are at this item: ${item}');
console.log('And we are at this index: ' + currentIdx);

if ($(item).hasClass('isHidden')) {
$(item).removeClass('isHidden').addClass('isActive')
}
currentIdx++
}, 3000);
}
}


/*$item.removeClass('isHidden').addClass('isActive).setTimeout(function() { $( this ).animate( { scrollLeft: 200 + 'px' } ), '500', 'swing', function() { console.log('Animation completed') } }) */
cycleItems();
});

html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
background: black;
}
.container {
display: inline;
//border: 1px solid white;

}
.slide {} .isActive {
visibility: visible;
}
.isHidden {
visibility: hidden;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=container>
<img class='isActive' src="http://placehold.it/350x150">
<img class='isHidden' src="http://placehold.it/350x150">
<img class='isHidden' src="http://placehold.it/350x150">
<img class='isHidden' src="http://placehold.it/350x150">
</div>




Answer

try this:

$(function() {
//var timer = 3000;

var $items = $('img','.container');
var currentIdx = 0;

var cycleItems = function() {
console.log('Running from cycleItems');

  $items.each(function(index, item){
    setTimeout(function() {

      console.log(`We are at this item: ${index}`);
      console.log('And we are at this index: ' + currentIdx );
      $(item).removeClass('isHidden').addClass('isActive') 
      /*if ( $(item).hasClass('isHidden') ) {

       } */
      currentIdx++
     }, 3000*index);
 });
}

     /*$item.removeClass('isHidden').addClass('isActive).setTimeout(function()   { $( this ).animate( { scrollLeft: 200 + 'px' } ), '500', 'swing',     function() { console.log('Animation completed') } }) */
cycleItems();
});

it's important to multiply the timer with the index otherwise you'll get your timer working only once.