how do i Loop .next()?

itsMe picture itsMe · Mar 26, 2013 · Viewed 14.5k times · Source

I have 3 divs with same class, i am adding class 'selected' to NEXT DIV on click and removing it from previous class, its working fine but I want to loop it

Currently its going from 1 --> 2 --> 3, I want it to loop, 3-->1, please help...

HTML

<div id="all">
<div class="section selected">ONE</div>
<div class="section">TWO</div>
<div class="section">THREE</div>
</div>
<br />
<a href="javascript:;" id="button">CLICK</a>

CSS

.selected{background:red}

JS

$('#button').click(function(){
    $('.section.selected').removeClass('selected').next('.section').addClass('selected'); 
});

JS Fiddle Link : http://jsfiddle.net/madhuri2987/KK66g/2/

Answer

Explosion Pills picture Explosion Pills · Mar 26, 2013

The simplest way would just be to check whether .next() exists and if not "select" the first.

var $next = $('.section.selected').removeClass('selected').next('.section');
if ($next.length) {
    $next.addClass('selected'); 
}
else {
    $(".section:first").addClass('selected');
}

http://jsfiddle.net/KK66g/3/