Changing Css Background Color With Javascript Variables
Solution 1:
You should change only background-color
property:
document.getElementById('changeBox').style.backgroundColor = "rgb(" + randR + ", " + randG + ", " + randB + ")";
In this case remove tailing ;
to make value valid.
Demo:http://jsfiddle.net/zc16vmjt/
Another thing is that document.write
is not very good practice. It's easy to avoid it in this case and go with appendChild
:
var box = document.getElementById('changeBox');
var randR = Math.floor(Math.random() * 255) + 1;
var randG = Math.floor(Math.random() * 255) + 1;
var randB = Math.floor(Math.random() * 255) + 1;
box.appendChild(document.createTextNode(randR + ", " + randG + ", " + randB));
box.style.backgroundColor = "rgb(" + randR + ", " + randG + ", " + randB + ")";
Solution 2:
Don't directly assign to style
. Assign to style.backgroundColor
.
Solution 3:
Each time when you:
document.write();
You are overwriting what's in the body of the entire document, removing the div entirely.
var randR = Math.floor(Math.random() * 255) + 1;
var randG = Math.floor(Math.random() * 255) + 1;
var randB = Math.floor(Math.random() * 255) + 1;
document.getElementById('changeBox').style.backgroundColor = "rgb(" + randR+ "," + randG+ "," + randB + ")";
Try this and you should be fine. If you want to see the values, output to a separate div; Just don't overwrite the entire document with document.write();
Solution 4:
You have an extra semi-colon and are missing a closing quotation mark.
To keep track of your nested quotes, it's a good idea to alternate between single and double quotes. Doing so makes it easier to realize that after the closing parenthesis, there should be a quote mark to close that and that should be followed by a quote that matches the beginning quote, before background-color.
var theBox = document.getElementById('changeBox');
theBox.style = "background-color: rgb('+ randR+ ',' +randG+ ','+randB+')'";
Post a Comment for "Changing Css Background Color With Javascript Variables"