How to: Set an Element’s text color based on it’s background color

Ever want to change your text color based on the value of the background it lies on? Me too.

Here is some code that allows you to get a decimal value from a hex value (#333333) and you can then set the text color to either light or dark depending on that value, check it out:

//Using jQuery to get/set the values
$().ready(function(){

    var hex = $('input').css('background-color');

    if(getBrightness(hex) < 50){
        $('input').css('color','#FFFFFF');
    } else {
        $('input').css('color','#000000');
    }

});

function getBrightness(hex) {
    var hex = hex.replace('#','');

    var c_r = hexDec(hex.substr(0, 2));
    var c_g = hexDec(hex.substr(2, 2));
    var c_b = hexDec(hex.substr(4, 2));

    return ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000;
}

function hexDec(hex_string){
    hex_string = (hex_string+'').replace(/[^a-f0-9]/gi, '');
    return parseInt(hex_string, 16);
}

Works like a charm ;)

Friday, July 16th, 2010 Javascript, jQuery

Leave a Reply

You must be logged in to post a comment.

[ad code=1 align=center]