0
function myFunction() {
var var1 = 5;
var var2 = 50;
var var3 = 100;
document.body.style.backgroundColor = "#" + (255-var1) + (255-var2) + (255-var3);
};

How can I convert the value inside the parentheses to hexadecimal value?
Ultimately, the value would be #FACD9B (Just an example)
Thank you in advance!

Willy Pt
  • 1,795
  • 12
  • 20
Dr. Owning
  • 171
  • 2
  • 14

4 Answers4

4
"#" + (255-var1).toString(16) + (255-var2).toString(16) + (255-var3).toString(16)
Farzher
  • 13,934
  • 21
  • 69
  • 100
4

You could use rgb instead of hex color codes in order to make it particularly simple, as well.

document.body.style.backgroundColor= 'rgb(' + (255-var1) + ',' + (255-var2) + ',' + (255-var3) + ')';
JBzd
  • 715
  • 3
  • 12
0

If you're trying to create a color via three variables, what you want is probably RGB format (x, y, z), not hex (#xxxxxx). So it'd be something like:

document.body.style.backgroundColor = 
"rgb(" + (255-var1) + "," + (255-var2) + "," + (255-var3) + ")"

which would output something like

"rgb(247,205,155)"

which is a valid way to declare a color in CSS/HTML.

jack
  • 2,894
  • 1
  • 13
  • 23
0

Check this answer

Which tells about the rgbtohex function by @Tim Down

Use it like this

document.body.style.backgroundColor = rgbToHex(var1, var2, var3);
Community
  • 1
  • 1