Determine If A Color Is Bright Or Dark Using JavaScript

August 7, 2018 by Andreas Wik

Finding out whether a color is light or dark can be really handy when working with dynamic content. Let’s say you have a profile page and the user can set their own page background color. You could then set the color of the text on top depending on the background color’s brightness.

The JavaScript function below speaks for itself with the comments. It takes a color as the argument, calculates the color’s HSP value, and uses that to determine whether the color is light or dark.

Ofcourse you can tweak this to change the threshold so it fits your needs.

The function lightOrDark:


function lightOrDark(color) {

    // Variables for red, green, blue values
    var r, g, b, hsp;
    
    // Check the format of the color, HEX or RGB?
    if (color.match(/^rgb/)) {

        // If RGB --> store the red, green, blue values in separate variables
        color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
        
        r = color[1];
        g = color[2];
        b = color[3];
    } 
    else {
        
        // If hex --> Convert it to RGB: http://gist.github.com/983661
        color = +("0x" + color.slice(1).replace( 
        color.length < 5 && /./g, '$&$&'));

        r = color >> 16;
        g = color >> 8 & 255;
        b = color & 255;
    }
    
    // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
    hsp = Math.sqrt(
    0.299 * (r * r) +
    0.587 * (g * g) +
    0.114 * (b * b)
    );

    // Using the HSP value, determine whether the color is light or dark
    if (hsp>127.5) {

        return 'light';
    } 
    else {

        return 'dark';
    }
}

Play with it using the CodePen below. Change the background-color of #profile-bio and hit the button to see it in action.

See the Pen YjJqpK by Andreas Wik (@andreaswik) on CodePen.

 

Stay safe out there!

Share this article

Recommended articles