# jQuery - addClass ACTIVE--> set timeout --> cycle (ok)(online.vinmec.com)

Đã hoàn thành (ok)

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery.js"></script>
  <style type="text/css">
    .active {
      color: red;
    }
  </style>
  <title>Document</title>
</head>
<body>
  <div id="div-1" class="cssClass">a</div>
  <div id="div-2" class="cssClass">b</div>
  <div id="div-3" class="cssClass">c</div>
  <div id="div-4" class="cssClass">d</div>
  <div id="div-5" class="cssClass">e</div>
  <script type="text/javascript">
    (function($) {
    $.fn.cycle = function(timeout, cls) {
      var l = this.length, current = 0, prev = 0, elements = this;
      function next() {
        elements.eq(prev).removeClass(cls);
        elements.eq(current).addClass(cls);
        prev = current;
        current = (current + 1) % l;
        setTimeout(next, timeout);
      }
      setTimeout(next, timeout);
      return this;
    };
    }(jQuery));
    $('div').cycle(1000, 'active');
  </script>
</body>
</html>
```

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1E4Gk2ppVKb4olmnun%2F-MYNjsKrT3UIvtKqDk-1%2F-MYNk7zQZu5v96aSS848%2FScreenshot_1.jpg?alt=media\&token=2ce4cf39-071c-47f8-8642-1ba34a8f7a95)

## [jQuery - addClass ACTIVE--> set timeout --> cycle](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle)

[Ask Question](https://stackoverflow.com/questions/ask)Asked 9 years, 11 months agoActive [8 years ago](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle?lastactivity)Viewed 2k times2

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?)[jquery](https://stackoverflow.com/questions/tagged/jquery)[Share](https://stackoverflow.com/q/5789621)[Improve this question](https://stackoverflow.com/posts/5789621/edit)Follow[edited Apr 6 '13 at 23:45](https://stackoverflow.com/posts/5789621/revisions)[![](https://www.gravatar.com/avatar/1b9f56786ceba3c57d0d2fe56182a4d3?s=32\&d=identicon\&r=PG)](https://stackoverflow.com/users/203458/kate-gregory)[Kate Gregory](https://stackoverflow.com/users/203458/kate-gregory)18.5k88 gold badges5353 silver badges8585 bronze badgesasked Apr 26 '11 at 11:26[![](https://i.stack.imgur.com/qCWYU.jpg?s=32\&g=1)](https://stackoverflow.com/users/383904/roko-c-buljan)[Roko C. Buljan](https://stackoverflow.com/users/383904/roko-c-buljan)162k3232 gold badges259259 silver badges274274 bronze badges[Add a comment](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle)

### 5 Answers

[Active](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle?answertab=active#tab-top)[Oldest](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle?answertab=oldest#tab-top)[Votes](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle?answertab=votes#tab-top)7

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**](http://jsfiddle.net/fkling/KMgxg/)

**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**](http://jsfiddle.net/fkling/KMgxg/1/)

You could also make the function accept an index where to start....[Share](https://stackoverflow.com/a/5789680)[Improve this answer](https://stackoverflow.com/posts/5789680/edit)Follow[edited Apr 26 '11 at 12:13](https://stackoverflow.com/posts/5789680/revisions)answered Apr 26 '11 at 11:33[![](https://i.stack.imgur.com/4P5DY.jpg?s=32\&g=1)](https://stackoverflow.com/users/218196/felix-kling)[Felix Kling](https://stackoverflow.com/users/218196/felix-kling)698k160160 gold badges996996 silver badges10631063 bronze badges

* @Alnitak: Oops, thanks :) That is from too much playing around ;) – [Felix Kling](https://stackoverflow.com/users/218196/felix-kling) [Apr 26 '11 at 12:12](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6637593_5789680)&#x20;
* @Felix: True, jQuery is so much fun! Thanks a lot for this great solution! I'm playing around with it too :) Kling you are a king! ...Where is the '+100' button? :) – [Roko C. Buljan](https://stackoverflow.com/users/383904/roko-c-buljan) [Apr 26 '11 at 13:46](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6639140_5789680)&#x20;
* @Felix kling--> argh! I have problems to stop the above on hover **if THIS CONTAINER DIV have class 'stop'**... may you help please?! How can i stop cycle on hover and restart on mouseout? – [Roko C. Buljan](https://stackoverflow.com/users/383904/roko-c-buljan) [Apr 27 '11 at 10:01](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6654365_5789680)&#x20;
* 1\@roXon: Ok. I have created "something" but I don't know whether it is a good approach. You can see a demo here: [jsfiddle.net/fkling/KMgxg/3](http://jsfiddle.net/fkling/KMgxg/3/) – [Felix Kling](https://stackoverflow.com/users/218196/felix-kling) [Apr 27 '11 at 10:45](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6654979_5789680)
* @Felix --> Carissimo Felix, grazie x il tuo tempo e l'aiuto! here is a malfunctioning demo :) [DEMO](http://roko.x10.mx/rox_gallery/) I have now problems with a false load and after click --> messy 'active' buttons :( – [Roko C. Buljan](https://stackoverflow.com/users/383904/roko-c-buljan) [Apr 27 '11 at 12:48](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6657084_5789680)&#x20;

[Show **12** more comments](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle)2

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);
```

[Share](https://stackoverflow.com/a/5789689)[Improve this answer](https://stackoverflow.com/posts/5789689/edit)Followanswered Apr 26 '11 at 11:33[![](https://www.gravatar.com/avatar/f4e48e531122e40e4105080200c59894?s=32\&d=identicon\&r=PG)](https://stackoverflow.com/users/295508/johnp)[JohnP](https://stackoverflow.com/users/295508/johnp)47.2k1010 gold badges100100 silver badges133133 bronze badges[Add a comment](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle)2

```
function changeClass() {
    if ($(".active").next(".cssClass").length > 0) {
        $(".active").removeClass("active").next(".cssClass").addClass("active");
    }
    else {
        $(".active").removeClass("active");
        $(".cssClass").first().addClass("active");
    }
    setTimeout(changeClass, 1000); // 1000ms = 1sec
}
```

And then just call `changeClass()` once to get the ball rolling.

edit: updated with something that should actually work. (again)[Share](https://stackoverflow.com/a/5789664)[Improve this answer](https://stackoverflow.com/posts/5789664/edit)Follow[edited Apr 26 '11 at 12:50](https://stackoverflow.com/posts/5789664/revisions)answered Apr 26 '11 at 11:30[![](https://i.stack.imgur.com/mhn8t.png?s=32\&g=1)](https://stackoverflow.com/users/206410/chris-mcfarland)[Chris McFarland](https://stackoverflow.com/users/206410/chris-mcfarland)5,82744 gold badges4343 silver badges6060 bronze badges

* Pretty good, but I'd take `changeClass()` out of a string; just pass the reference. – [alex](https://stackoverflow.com/users/31671/alex) [Apr 26 '11 at 11:32](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6636968_5789664)
* Nice, not sure if it will loop back to `div-1` after `div-5` though? – [codeulike](https://stackoverflow.com/users/22194/codeulike) [Apr 26 '11 at 11:33](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6636984_5789664)
* Yeh was just wondering, once `.next()` gets to the end if it would just stop? Might need to check `.next().length` and make it use `.first()` instead, if `.next().length` is `0`. – [Chris McFarland](https://stackoverflow.com/users/206410/chris-mcfarland) [Apr 26 '11 at 11:36](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6637024_5789664)
* Passing a string to `setTimeout` is not good. Pass a function reference. – [Felix Kling](https://stackoverflow.com/users/218196/felix-kling) [Apr 26 '11 at 11:41](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6637099_5789664)
* So just `setTimeout(changeClass(), 1000)`? – [Chris McFarland](https://stackoverflow.com/users/206410/chris-mcfarland) [Apr 26 '11 at 11:43](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle#comment6637127_5789664)

[Show **1** more comment](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle)1

Here's my example :).

<http://jsfiddle.net/8ByyN/>[Share](https://stackoverflow.com/a/5789854)[Improve this answer](https://stackoverflow.com/posts/5789854/edit)Followanswered Apr 26 '11 at 11:50[![](https://i.stack.imgur.com/8mRNV.jpg?s=32\&g=1)](https://stackoverflow.com/users/244727/mingos)[mingos](https://stackoverflow.com/users/244727/mingos)21.7k1111 gold badges6868 silver badges105105 bronze badges[Add a comment](https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle)1

First try.

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">

</script>

<style type="text/css">
    .active
    {
        font-weight:bold;    
    }
</style>




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

<button onclick="int=window.clearInterval(int)">Stop</button>


<script type="text/javascript">

    function toggleActive() {

        if ($(".cssClass:last").hasClass("active")) {
            console.warn("last element reached");
            $(".cssClass:last").toggleClass("active");
            $(".cssClass:first").toggleClass("active");
        }
        else {
            $(".active").first().toggleClass("active").next().addClass("active");
        }

    }
     var int;
    $(function () {

        int= self.setInterval("toggleActive()", 1000);

    });
</script>
```

Hope this helps.
