views:

216

answers:

4

This is my code to switch the class of my body tag when a user clicks a link.

function switchBodyColor() {
    if (document.body.className == 'blue')
        document.body.className = 'red';
    else if (document.body.className == 'red')
        document.body.className = 'green';
    else if (document.body.className == 'green')
        document.body.className = 'blue';
}

I want to set the resulting color as a variable called bodyColor. So if the body class is "blue" and the user clicks and switches it to "red" I want to store red as a variable (bodyColor) for other uses later on. Or better yet, set document.body.className as a variable itself and then switch out document.body.className in the switchBodyColor() function with that variable.

I thought something along the lines of:

    if (document.body.className == 'blue')
        document.body.className = 'red',
        var bodyColor = red;

or

var bodyColor = document.body.className

to set the body class as a variable.

Of course neither of those two options work. ^_^; How can I accomplish either (or both) of the above?

+2  A: 

I would write a function and an array for this:

var classNames = { 'blue': 'red', 'red': 'green', 'green': 'blue' };

function setBodyClass( className ) {
   document.body.className = className;
   bodyColor = className;
}

function switchBodyColor() {
   var newClass = classNames[ document.body.className ];
   if( newClass.length ) { //body.className is in the array.
       setBodyClass( newClass );
   }
}

This of course is assuming that the bodyColor and classNames variables are in global scope.

Jacob Relkin
+1 for replacing "if" sequence with object
outis
@outis: thanks :)
Jacob Relkin
thanks for another very good alternative to the how I was doing it.
George
+2  A: 

You need your variable to be global:

var bodyColor = 'red';  // Global var, initialized to your first color class

function switchBodyColor() {
    if (document.body.className == 'blue')
        document.body.className = 'red';
    else if (document.body.className == 'red')
        document.body.className = 'green';
    else if (document.body.className == 'green')
        document.body.className = 'blue';


    bodyColor = document.body.className;
    alert(bodyColor);
}

In your other example, you also need to put quotes around your color string:

 bodyColor = "red";



Another way to do this might be to number your color classes, which will let you use simple arithmetic to change your classes and allows you to easily change the number of classes you are cycling through.

var colorNum = 0;
var totalColors = 3;

function switchBodyColor() {
    colorNum = (colorNum+1)%totalColors;
    document.body.className = 'color'+colorNum;
}

You css would be:

.color0 { background-color: blue; }
.color1 { background-color: red; }
.color2 { background-color: green; }

Or whatever your color class definitions are.

Jeff B
thanks, this answers my question in the most simplistic way possible in addition to giving me an alternative not much harder to implement.
George
+2  A: 

If you want to set a global variable then you will have to declare it outside the function, so that your other functions can access it. So it would be like

var bodyColor;

function switchBodyColor() {
    if (document.body.className == 'blue')
    {
        document.body.className = 'red';
    }
    else if (document.body.className == 'red')
    {
        document.body.className = 'green';
    }
    else if (document.body.className == 'green')
    {
        document.body.className = 'blue';
    } 

    bodyColor = document.body.className;
}

You can also replace the if else if statement with a switch case block.

rahul
+5  A: 

You could store the colors in an array, then by manipulation always use the first color in the array as the current color:

var bodyColors = ['blue','red','green'];

function switchBodyColor(){
   bodyColors.push(bodyColors.shift()); // Move first item to the end
   document.body.className = bodyColors[0];
}

And then anywhere you need it in your app, just call:

bodyColors[0]; // Will refer to the current body class

Optional Check for Initial State

The previous code assumes your body element always starts with blue. If that is not the case, you could add this one-time run 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 would make sense to use an Array because its order is always honored. However since there is no "indexOf" in at least IE7 and below, we have no way of matching the current color to its position in the array without a loop.

This is where the Array.shift and Array.push commands come into play. Array.shift removes the first element in the array, and returns it. Array.push takes what is passed to it, and "pushes" it onto the end of the array. By combining the two methods together we can take the first item and move it to the end, creating a carousel of sorts:

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 honored and the first element is always set to what we want, thus bodyColor[0] is always the current color.

Doug Neiner
wow, i have never used `shift()`
Rakesh Juyal
@Rakesh I am always amazed at the little functions I never knew about that change how I code. The `Array` in JS has `shift`, `unshift`, `push`, and `pop`. Just remember that `push` and `unshift` return the new number of items in the array, and that `pop` and `shift` return the removed item.
Doug Neiner
this makes sense to me, but it's more complicated than what I'm looking for at the moment. I'm trying to practice more common javascript functions to learn, but this is a great variation of the other array answer given!
George
@George I updated my answer so you can understand what is going on better. I promise `Array.shift` and `Array.pop` aren't crazy weird functions :)
Doug Neiner
Thanks for the additional explanation Doug. Can you just clarify what console.log(c); is?
George