How Can You Programmatically Change Font Color Based on the Background? (Light/Dark Mode)
If you’ve visited Martech Zone lately, you may have noticed that we now offer the ability to view the site in either light or dark mode. Just search for the moon or sun icon next to the date in the top left navigation bar on the site.
It’s a pretty cool feature and it works really well. When I launched a new conversion tool to change HEX to RGB, I wanted to actually display the color that the user was trying to calculate. I not only display the color, but I also added a nice feature that displayed the name of the color. But that introduced an issue…
If the swatch that displayed the color had a light background, you wouldn’t be able to read the text that I generate dynamically for the swatch. So… I had to create a function that set the font color based on background color and whether or not there was enough contrast to view the font.
function contrast(hex) {
var threshold = 149;
let r = 0, g = 0, b = 0;
// 3 digits
if (hex.length == 4) {
r = “0x” + hex[1] + hex[1];
g = “0x” + hex[2] + hex[2];
b = “0x” + hex[3] + hex[3];
// 6 digits
} else if (hex.length == 7) {
r = “0x” + hex[1] + hex[2];
g = “0x” + hex[3] + hex[4];
b = “0x” + hex[5] + hex[6];
}
return ((r*0.299 + g*0.587 + b*0.114) > threshold) ? ‘#000000’ : ‘#ffffff’;
}