Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery infinite loop through each div

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);
});
like image 909
Dentor Uman Avatar asked Dec 21 '22 20:12

Dentor Uman


2 Answers

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);​
like image 179
Andy Avatar answered Jan 11 '23 14:01

Andy


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/

like image 32
VisioN Avatar answered Jan 11 '23 14:01

VisioN