Kyle93
Kyle93

Reputation: 795

JS - Setting Div background color using a variable

Well basically, one of my mates was practicing JS and he had an idea of a test basic site. So I said we would have a race to complete it. We have both run in to an error at this point. We have created a color in JS. However when we need to output it does not work. I have this.

document.getElementById("outputColor").style.backgroundColor=currentColor;

Where current color is made via this

part1 = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
part2 = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
part3 = Math.floor(Math.random() * (255 - 0 + 1)) + 0;
currentColor = "\"rgb (" + part1 + ", " + part2 + ", " + part3 + ")\"";

Putting current color in "" would mean it's expecting the value of currentColor. Not the actual variable value.

Hope that makes sense. Is this possible, or are we barking up the wrong tree?

Thanks

Edit: It does have a css style assosiated with it already

#outputColor
{
    height: 100px;
    width: 100px;
    background-color: rgb(0,0,0);
}

Edit: Solved, solution is

currentColor = "rgb(" + part1 + ", " + part2 + ", " + part3 + ")";

Thank you all!

Upvotes: 4

Views: 3593

Answers (3)

Dr.Molle
Dr.Molle

Reputation: 117334

There are too much double-quotes, use this:

currentColor = "rgb(" + part1 + ", " + part2 + ", " + part3 + ")";

Upvotes: 4

The Alpha
The Alpha

Reputation: 146201

currentColor = "rgb(" + part1 + ", " + part2 + ", " + part3 + ")"; // RGB

OR Using Hex format

currentColorHex="#"+(part1).toString(16)+(part2).toString(16)+(part3).toString(16);

DEMO.

Upvotes: 1

MARP
MARP

Reputation: 581

currentColor = "rgba(" + part1 + ", " + part2 + ", " + part3 + ",0)";

Upvotes: 1

Related Questions