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?
You need your variable to be global:
In your other example, you also need to put quotes around your color string:
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.
You css would be:
Or whatever your color class definitions are.