0

I have a line of JavaScript that allows me to make the background of my webpage a different colour each time the page is loaded:

document.getElementById("band").style.background = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

For visibility, I want to have the font be either black or white, depending on whether the background is dark or light.

For example, I think the "halfway" point in hexadecimal is #800000.

I want my script to tell my webpage to use white font if the hexadecimal number is less than 800000 and use black font if the hexadecimal number is more than 800000.

3
  • 3
    RGB is the worst colour model to do that. You'll possibly need to convert to HSL. Commented Feb 7, 2018 at 15:41
  • 1
    You can't treat RGB values like actual hex numbers. Compare 0x7fffff to 0x800001, for example.
    – Siguza
    Commented Feb 7, 2018 at 15:41
  • Ah I see. So should I use the script I have in my question and THEN convert to HSL and THEN put the IF condition in? Commented Feb 7, 2018 at 15:45

1 Answer 1

1

You can use TinyColor library

var color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

document.write("<b style=\"color:" + color + ";\">" + color + "<\/b> is ");

var c = tinycolor(color);

if (c.isDark()) 
  document.write("Dark");
else 
  document.write("Light");
<script src="https://rawgit.com/bgrins/TinyColor/master/tinycolor.js"></script>

Not the answer you're looking for? Browse other questions tagged or ask your own question.