I have some divs with divs in them, which I want to loop through while removing a class from the current one, then adding a class to the next one.
Then when I reach the last one, I want to go back to the start and do it all over again.
I already have a way of doing this, but it only works for one set of divs, I'm going to be having many sets of divs that need to loop independently.
Here's an example few sets (there would be a random amount of divs in each):
<div class="set">
<div class="current">Item1</div>
<div>Item2</div>
<div>Item3</div>
</div>
<div class="set">
<div class="current">Item1</div>
<div>Item2</div>
<div>Item3</div>
<div>Item4</div>
<div>Item5</div>
</div>
I need to remove that current class, and add it to the next div in each set, and so on.
Here is the code I have that works with one set:
$(function() {
var items = $('.set div').length;
current = 0;
setInterval(function() {
$('.set div').eq(current).removeClass('current');
if (current == items - 1){
current = 0;
} else {
current++;
}
$('.set div').eq(current).addClass('current');
}, 500);
});
my take:
http://jsfiddle.net/yyY28/
$('.set').each(function(){
(function($set){
setInterval(function(){
var $cur = $set.find('.current').removeClass('current');
var $next = $cur.next().length?$cur.next():$set.children().eq(0);
$next.addClass('current');
},1000);
})($(this));
});
version 2:
setInterval(function(){
$('.set').each(function(){
var $cur = $(this).find('.current').removeClass('current');
var $next = $cur.next().length?$cur.next():$(this).children().eq(0);
$next.addClass('current');
});
},1000);
Maybe I didn't get you right, but is that you are looking for?
function loop() {
$(".set").each(function() {
var current = $(this).children(".current").removeClass("current");
var i = current.next().length ? current.index() : 0;
current.siblings(":eq(" + i + ")").addClass("current");
});
}
setInterval(loop, 500);
DEMO: http://jsfiddle.net/jGcsh/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With