dynamic
dynamic

Reputation: 48121

Cycle through divs?

I have this HTML:

<div id="container">

<div class="boxes">first box</div>
<div class="boxes">second box</div>
<div class="boxes">third box</div>

</div>

<a href="jquery">Show me next box</a>

Consider that initially only the first box is visible. When I click 'Show me next box' I want the current visible box to be hidden, and the next .boxes on the list to appear.

The only thing that I think it gets close is the .each function, but I shouldn't cycle through all divs just to show one, I think.

Upvotes: 2

Views: 2198

Answers (2)

user578895
user578895

Reputation:

$('a').click(function(){
    $('.boxes').filter(':visible').hide().next().add('.boxes:first').last().show();
});

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

$('a').click(function() {
    var visibleBox = $('#container .boxes:visible');
    visibleBox.hide();
    var nextToShow = $(visibleBox).next('.boxes:hidden');
    if (nextToShow.length > 0) {
        nextToShow.show();
    } else {
        $('#container .boxes:hidden:first').show();
    }
    return false;
});

Live demo.

Upvotes: 5

Related Questions