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

https://stackoverflow.com/questions/5789621/jquery-addclass-active-set-timeout-cycle

Đã 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>

Ask QuestionAsked 9 years, 11 months agoActive 8 years agoViewed 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?)jqueryShareImprove this questionFollowedited Apr 6 '13 at 23:45Kate Gregory18.5k88 gold badges5353 silver badges8585 bronze badgesasked Apr 26 '11 at 11:26Roko C. Buljan162k3232 gold badges259259 silver badges274274 bronze badgesAdd a comment

5 Answers

ActiveOldestVotes7

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....ShareImprove this answerFollowedited Apr 26 '11 at 12:13answered Apr 26 '11 at 11:33Felix Kling698k160160 gold badges996996 silver badges10631063 bronze badges

Show 12 more comments2

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

ShareImprove this answerFollowanswered Apr 26 '11 at 11:33JohnP47.2k1010 gold badges100100 silver badges133133 bronze badgesAdd a comment2

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)ShareImprove this answerFollowedited Apr 26 '11 at 12:50answered Apr 26 '11 at 11:30Chris McFarland5,82744 gold badges4343 silver badges6060 bronze badges

Show 1 more comment1

Here's my example :).

http://jsfiddle.net/8ByyN/ShareImprove this answerFollowanswered Apr 26 '11 at 11:50mingos21.7k1111 gold badges6868 silver badges105105 bronze badgesAdd a comment1

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.

Last updated

Was this helpful?