Damien Damien - 4 months ago 8
HTML Question

Using jQuery .each() to infinitely loop over elements

I have a set of elements like this

<div class="wrap">
<div class="block active">
<p>content</p>
</div>
<div class="block">
<p>content</p>
</div>
<div class="block">
<p>content</p>
</div>
<div class="block">
<p>content</p>
</div>
</div>


I need a function to infinitely loop on these elements (block) moving the active class from one to the next. I've looked at using .each() for this but I don't really understand how to use it. Any help is greatly appreciated.

Answer

I think you want to do it in an interval, this is pretty easy in your case:

setInterval(function() {
    var index = $(".block.active").removeClass("active").index();
        index = index + 1 >= $(".block").length ? 0 : ++index;

    $(".block:eq(" + index + ")").addClass("active");
}, 500);
div.active { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <div class="block active">
    <p>content</p>
  </div>
  <div class="block">
    <p>content</p>
  </div>
  <div class="block">
    <p>content</p>
  </div>
  <div class="block">
    <p>content</p>
  </div>
</div>