I'd like to change the color of the sqaure (#myID: width = height = 100px) every second. (To check if that switch loop works, in every "case" I wrote console.log("smth happened");.)
But the color of this square does not change. "FIDDLE"
Next thing, every second document.getElementById('myID') is written to a new formed variable thesquare. How to make the variable global, outside the function?
Javascript:
var i = 0;
function changecolor()
{
var thesquare = document.getElementById('myID');
switch (i)
{
case 0 :
thesquare.setAttribute("background-color","red");
++i;
break;
case 1 :
thesquare.setAttribute("background-color","green");
++i;
break;
default :
thesquare.setAttribute("background-color","blue");
i=0;
break;
}
}
setInterval("changecolor()",1000);
It is not an attribute you want to set but a style
:
thesquare.style.backgroundColor = 'red';
Your function does work but the attribute background-color
does not do anything.
Also, setInterval("changecolor()",1000);
should be setInterval(changecolor,1000);
Fiddle
Next thing, every second document.getElementById('myID') is written to
a new formed variable thesquare. How to make the variable global,
outside the function?
You don't need to use a global, you can keep it in an outer scope using a closure and an immediately invoked function expression (IIFE):
(function() {
var thesquare = document.getElementById('myID');
var i = 0;
function changecolor() {
switch (i) {
case 0 :
thesquare.style.backgroundColor = "red";
++i;
break;
case 1 :
thesquare.style.backgrounColor = "green";
++i;
break;
default :
thesquare.style.backgroundColor = "blue";
i=0;
break;
}
}
setInterval(changecolor, 1000);
}());
Note that setInterval will run at about, not exactly, the specified interval. It will slowly lose time.
You can shorten the code by replacing the entire switch block with something like:
var colours = ['red','green','blue']
thesquare.style.backgroundColor = colours[i++ % colours.length];