Check out my fiddle here
Here is the js in question:
$(document).ready(function() {
$(\'.clickMe\').toggle(
function() {
$(\
DRYing it a bit:
var counter = 0;
var colors = [
"#eeeeee",
"#00ff00",
"#ff0000",
"#000000"
];
var $div = $('#coloredDiv');
$('.clickMe').click(function(){
$div.css({
"background-color": colors[(counter++)%colors.length]
})
});
With the modulo operator [%
], you loop over the array without exceeding its bounds [a%b
evaluates to b-1
at most].
EDIT: you just increment the counter, then the modulo will "reset" it to 0 every array.length
iterations [it won't be reset actually, just the result of the expression will look like]. Search wikipedia for modulo operator, you will find out a lot of interesting properties.
i | (i++)%arr.length
---------
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 0 |
| 5 | 1 |
| 6 | 2 |
| 7 | 3 |
...