1. Looping an index counter with Reminder %
http://jsbin.com/howon/5/edit
var colors = ["red", "green", "blue"],
i = 0,
n = colors.length;
$(document).keydown(function(e){
var k = e.which;
if(k==38||k==40){
i = (k==38? ++i : --i) <0? n-1 : i%n;
$('#test').attr('class', colors[i]);
}
});
2. Manipulating internally the Array
Another interesting (less complicated) way to do it, without using a current index counter
is to manipulate the Array it-self by simply pushing the last key to the first position (or inverse, first to last) and always get the [0] index key:
http://jsbin.com/jojupo/3/edit
var colors = ["red", "green","blue"];
$(document).keydown(function(e){
var k = e.which;
if(k==38||k==40){
if (k==38) colors.push(colors.shift());
else if (k==40) colors.unshift(colors.pop());
$('#test').attr('class', colors[0]);
}
});