truslivii.lev
truslivii.lev

Reputation: 701

Add class to the elements in the cycle ( jquery )

I need to add to class of the first three elements, then the next three, and so on in the cycle. I tried to use this code but id doesn't work.

$.fn.toggle_class = function () {
var lis = $(this).find('li'); 
var len = lis.lenght();

while(true) {
    for (var i = 0; i < len; i += 3) {
        first = i;
        second = i + 1;
        third = i + 2;
        lis.delay(100).removeClass('visible');
        lis.eq(first).addClass('visible');
        lis.eq(second).addClass('visible');
        lis.eq(third).addClass('visible');
    }
}

return $(this);
};

$('ul').toggle_class();

http://jsfiddle.net/2de3n/9/

What's wrong? How can I fix it ?

Upvotes: 1

Views: 124

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173562

Instead of a never ending loop, you should use setInterval() so that you can hand over the control back to the browser:

$.fn.toggle_class = function () {
    var lis = this.find('li'),
    len = lis.length,
    i = 0; // initialize pointer

    setInterval(function() {
        lis
          .removeClass('visible')
          .slice(i, i + 3)
          .addClass('visible');

        // advance pointer
        i = (i + 3) % len;
    }, 100);

    return this;
};

$('ul').toggle_class();

It's important that you only call this function once.

Demo

Upvotes: 1

Related Questions