Anytime you increment, check the new value. If it's greater than the total number of options, reset it to zero. If it's less than the total number of options, set it to the max. Else, simply +=1
or -=1
.
For example:
var total = 5,
currentNumber = 0,
numContainer = $("#number");
$(".up, .down").on("click", function(){
currentNumber = parseInt( numContainer.text(), 10 );
if ( $(this).hasClass("up") ) {
if ( ++currentNumber > total ) currentNumber = 1;
}
if ( $(this).hasClass("down") ) {
if ( --currentNumber < 1 ) currentNumber = total;
}
numContainer.text( currentNumber );
});
This could be further reduced to use the ternary operator as well as hack the functionality of the short-circuiting conjunction operator:
var t = 5, c = 0, n = $("#number");
$(".up, .down").on("click", function(){
c = parseInt( n.text(), 10 );
$(this).hasClass("up") ? (++c > t) && (c = 1) : (--c < 1) && (c = t);
n.text( c );
});
Demo: http://jsbin.com/egifas/edit#javascript,live