Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cycle through siblings using jQuery?

I have the folowing code:

html:

<div class="container">
    <div class="selected">A</div>
    <div>B</div>
    <div>C</div>
    <div>D</div>
</div>
<button id="next">next!</button>

jQuery:

$("#next").click(function() {
    $(".selected").removeClass("selected").next().addClass("selected");
});

What i want is loop through the divs in the container. I can do this to cycle:

$("#next").click(function() {
    if ($(".selected").next().length == 0) {
        $(".selected").removeClass("selected").siblings(":nth-child(1)").addClass("selected");
    }
    else {
        $(".selected").removeClass("selected").next().addClass("selected");
    }
});

But i think there is a simpler way. How can i make it simpler ? (I don't mind if you don't use the next() function).

jsFiddle: http://jsfiddle.net/S28uC/

like image 379
Benjamin Crouzier Avatar asked Sep 14 '11 10:09

Benjamin Crouzier


1 Answers

I 'd prefer siblings.first() instead of siblings(":nth-child(1)"), but in essence you won't be able to wrap around without using some variant of next().length.

Update: If I were writing this from scratch, this is how I 'd do it:

$("#next").click(function() {
    var $selected = $(".selected").removeClass("selected");
    var divs = $selected.parent().children();
    divs.eq((divs.index($selected) + 1) % divs.length).addClass("selected");
});

This approach is motivated by two factors:

  1. When you want to cycle over a collection indefinitely, modulo comes to mind
  2. Getting rid of the if makes for smarter-looking code

When setting the value of divs I preferred $selected.parent().children() over the equivalent $selected.siblings().add($selected) as a matter of taste -- there are practically endless possibilities.

like image 50
Jon Avatar answered Sep 19 '22 02:09

Jon