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 |
...
Don't know better or not but have a look at the following:
<div id="coloredDiv" data-index="-1"></div>
Note the data
attribute added to div.
var colors = ['#eeeeee', "#00ff00", "#ff0000", "#000000"];
$(document).ready(function () {
$colorDiv = $('#coloredDiv');
ln = colors.length;
$('.clickMe').on("click", function () {
var i = $colorDiv.data("index");
++i;
if (i >= ln) i = 0;
$colorDiv.css({
'background-color': colors[i]
});
$colorDiv.data("index", i);
});
});
Working fiddle is here.