I am having some trouble changing the color of the background on each refresh. Any help is appreciated. Here is my js so far:
var colors = ['#760CE8', '#4782B1', '#E8890C'];
var changeBackground = function() {
document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);
};
changeBackground();
I am having some trouble changing the color of the background on each refresh. Any help is appreciated. Here is my js so far:
var colors = ['#760CE8', '#4782B1', '#E8890C'];
var changeBackground = function() {
document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);
};
changeBackground();
Share
Improve this question
edited Apr 22, 2014 at 5:25
takendarkk
3,4428 gold badges27 silver badges38 bronze badges
asked Apr 22, 2014 at 5:22
WaymondWaymond
2572 gold badges6 silver badges21 bronze badges
2 Answers
Reset to default 4You're almost there.
In the line
document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);
you need to remove the parentheses surrounding [Math.floor(Math.random()*colors.length)]
.
Otherwise JS will think that you want to invoke colors
as a function.
Instead you want to access an array by index. That's what the square brackets do.
So change it to
document.body.style.background = colors[Math.floor(Math.random()*colors.length)];
and it will be fine.
Your code is fine just do as @TheShellfishMeme said and put your function in the body tag like this:
<body onload="changeBackground();">
now on every refresh you get the different body color.