user1551817
user1551817

Reputation: 7481

Creating an IF condition in JavaScript based on hexadecimal colors

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.

Upvotes: 0

Views: 321

Answers (1)

Maharramoff
Maharramoff

Reputation: 1031

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>

Upvotes: 1

Related Questions