Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - addClass ACTIVE--> set timeout --> cycle

Tags:

jquery

I have 5 elements with same class and at page-load the first div is active:

<div id="div-1" class="cssClass active"></div>
<div id="div-2" class="cssClass"></div>
<div id="div-3" class="cssClass"></div>
<div id="div-4" class="cssClass"></div>
<div id="div-5" class="cssClass"></div>

How to add a timeout before jQuery pass the active class to the second div and so on, reaching the last div and restart with the first div? and so on... (I would like to avoid the use of the jQuery Cycle plugin. Is there something simpler in a couple of lines?)

like image 573
Roko C. Buljan Avatar asked Jan 26 '26 22:01

Roko C. Buljan


2 Answers

You can write your own cycle plugin like this:

(function($) {
    $.fn.cycle = function(timeout, cls) {
        var l = this.length,
            current = 0,
            prev = -1,
            elements = this;

        function next() {
            elements.eq(prev).removeClass(cls);
            // or just `elements.removeClass(cls);`
            elements.eq(current).addClass(cls);
            prev = current;
            current = (current + 1) % l; // modulo for wrap around
            setTimeout(next, timeout);
        }
        setTimeout(next, timeout);
        return this;
    };
}(jQuery));

and use it like this:

$('div').cycle(2000, 'active');

DEMO

Update: Overlooked that the first div is already active. You can make the plugin detect the already active div by adding:

if(this.filter('.' + cls).length > 0) {
    current = this.index(this.filter('.' + cls)[0]) + 1;
    prev = current - 1 ;
}

DEMO

You could also make the function accept an index where to start....

like image 184
Felix Kling Avatar answered Jan 29 '26 12:01

Felix Kling


This should do it. Explanation in comments.

function moveClass() {
   if ($('.active:first').next()) {
      $('.active:first')
          .removeClass('active') //remove the current class
          .next() //move to the next
          .addClass('active'); // add the class to the next div
   } else {
      $('.active').removeClass('active');
      $('.cssClass:first').addClass('active'); //move to the first of the lot if there is no more next()
   }

}

$('.cssClass:first').addClass('active');
setInterval(moveClass, 5000);
like image 28
JohnP Avatar answered Jan 29 '26 11:01

JohnP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!