You can store colors in an array, and then by manipulating always use the first color in the array as the current color:
var bodyColors = ['blue','red','green']; function switchBodyColor(){ bodyColors.push(bodyColors.shift());
And then, anywhere you need it, in your application, just call:
bodyColors[0];
Optional baseline check
The previous code assumes your body element always starts with blue . If this is not the case, you can add this one-time startup code right below the switchBodyColor() function:
for(var i=0; i<bodyColors.length; i++){ if(document.body.className == bodyColors[i]) break; bodyColors.push(bodyColors.shift()); }
Additional explanation
Since you want the colors to always rotate in the same order, it makes sense to use an array because its order is always respected. However, since in IE7 and below there is no " indexOf ", we cannot match the current color with its position in the array without a loop.
The commands Array.shift and Array.push are used Array.push . Array.shift removes the first element in the array and returns it. Array.push takes what is passed to it and pushes it to the end of the array. By combining the two methods together, we can take the first element and move it to the end, creating a carousel:
var c = [1,2,3]; c.push(c.shift()); console.log(c); // Outputs [2,3,1] c.push(c.shift()); console.log(c); // Outputs [3,1,2] c.push(c.shift()); console.log(c); // Outputs [1,2,3]
Thus, the order is always respected, and the first element is always set the way we want, so bodyColor[0] always the current color.