Reputation: 13
This code shows no errors but is not working, can anyone see why?
function setStyles(){
var ya
styles=document.getElementById("back");
switch (ya){
case 1:styles.style.backgroundColor='#FF0000';
break;
case 2:styles.style.backgroundColor='#FF6600';
break;
case 3:styles.style.backgroundColor='#FFFF66';
break;
case 4:styles.style.backgroundColor='#669900';
break;
case 5:styles.style.backgroundColor='#000066';
break;
case 6:styles.style.backgroundColor='#660066';
break;
}
}
window.onload = setStyles;
Upvotes: 0
Views: 48
Reputation: 64536
None of the case statements will be matched because ya
is undefined. Try defining it (in other words give it a value):
var ya = 1;
You could also define a default
case which will be executed if none of the other case statements match:
...
...
case 6:
styles.style.backgroundColor='#660066';
break;
default:
styles.style.backgroundColor='#000000';
...
Edit: to get a random background color:
var ya = Math.floor(Math.random() * 6) + 1;
Upvotes: 0
Reputation: 11788
It works if you define ya:
function setStyles(ya){
var ya;
styles=document.getElementById("back");
switch (ya) {
case 1:
styles.style.backgroundColor='#FF0000';
break;
case 2:
styles.style.backgroundColor='#FF6600';
break;
case 3:
styles.style.backgroundColor='#FFFF66';
break;
case 4:
styles.style.backgroundColor='#669900';
break;
case 5:
styles.style.backgroundColor='#000066';
break;
case 6:
styles.style.backgroundColor='#660066';
break;
}
}
window.onload = function() {
setStyles(1);
};
http://jsbin.com/agajen/1/edit
Upvotes: 1