You will probably want to look at jQuery prev () and next () . Combined with logic based on the class name for the steps (instead of DOM identifiers), these methods can very easily shorten and simplify your code.
A rough detailed example:
$('#nextButton').click( function() { var current_step = $('#steps_container').find('.step:visible'); var next_step = current_step.next(); if (next_step.length) { current_step.hide(); next_step.fadeIn(250); } } ); $('#prevButton').click( function() { var current_step = $('#steps_container').find('.step:visible'); var prev_step = current_step.prev(); if (prev_step.length) { current_step.hide(); prev_step.fadeIn(250); } } );
This should perfectly handle any number of steps in the following markup:
<div id="steps_container"> <div class="step">Step 1</div> <div class="step">Step 2</div> <div class="step">Step 3</div> <div class="step">Step 4</div> <div class="step">Step 5</div> <div class="step">Step 6</div> ... </div>
While @stefanz improves my code, an even simpler and more general approach might be to associate navigation button handlers with a class, for example:
$('.steps_nav_buttons_bar .steps_nav_button').click( function() { var current_step = $('#steps_container').find('.step:visible'), new_step = $(this).hasClass('next') ? current_step.next() : current_step.prev(); if (new_step.length) { current_step.fadeOut('fast',function() { new_step.fadeIn('fast') }) } } );
The advantage of this is that it allows you to add more than one set of navigation buttons, for example, if you want the navigation bars to be above and below:
<div class="steps_nav_buttons_bar top_bar"> <div class="steps_nav_button prev">Prev</div> <div class="steps_nav_button next">Next</div> </div> <div id="steps_container"> <div class="step">Step 1</div> <div class="step">Step 2</div> <div class="step">Step 3</div> <div class="step">Step 4</div> <div class="step">Step 5</div> <div class="step">Step 6</div> ... </div> <div class="steps_nav_buttons_bar bottom_bar"> <div class="steps_nav_button prev">Prev</div> <div class="steps_nav_button next">Next</div> </div>
Boaz
source share