Reputation: 2399
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.
$(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>
Upvotes: 1
Views: 84
Reputation: 1667
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.
Upvotes: 1