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\')
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.