Reputation: 152
I've just starting to learn JavaScript, So I know only a few things about it. I have searched this question and I found the right code for it that works fine with hexadecimal color format. But before that i was trying sth on my own, Can you help me to turn it to an RGB color generator. Every time I add this code to my page it won't work.
document.getElementById("myButton").onclick = function() {
var r =Math.random();
r = 255*r;
r = Math.floor(r);
var g =Math.random();
g = 255*g;
g = Math.floor(g);
var b =Math.random();
b = 255*b;
b = Math.floor(b);
var color= "rgb(" + r +"," + g +"," +b ")";
document.getElementById("myDiv").style.background: color;
}
Upvotes: 1
Views: 115
Reputation: 1816
Change .style.background: color
to .style.backgroundColor = color
and that should do the trick.
EDIT
There's another syntax error in your code. You forgot a +
after specifying b
when initializing color
.
Upvotes: 3
Reputation: 1
Syntax error at missing +
following b
at
var color= "rgb(" + r +"," + g +"," +b ")";
also substitute =
for :
at
document.getElementById("myDiv").style.background = color;
for
document.getElementById("myDiv").style.background: color;
document.getElementById("myButton").onclick = function() {
var r = Math.random();
r = 255 * r;
r = Math.floor(r);
var g = Math.random();
g = 255 * g;
g = Math.floor(g);
var b = Math.random();
b = 255 * b;
b = Math.floor(b);
var color = "rgb(" + r + "," + g + "," + b + ")";
document.getElementById("myDiv").style.background = color;
}
div {
width:50px;
height:50px;
}
<button id="myButton">click</button>
<div id="myDiv"></div>
Upvotes: 3