Friday 22nd January 2010

by Stephen

I recently needed to programmatically darken dynamically generated colors using JavaScript. To do this I used the Underscore.js library. In Gecko and Webkit, $(‘elem’).css(‘background-color’) returns an RGB value, but in IE it returns a Hexadecimal value. This function checks for each and uses Underscore’s map function to quickly convert into a darker version of itself. Pass a color (c) and a decimal value (v) into darken and receive a darker RGB value.

function darken (color, value) {
    var rgb;
    if (/^rgb/.test(color)) {
         // If darkening an RGB color
        rgb = _.map(color.match(/\((\d+), ?(\d+), ?(\d+)\)/).slice(1), function(num){
            return parseInt(num, 10);
        });
    } else if (/^#/.test(color)) {
         // If darkening a Hexadecimal color
        rgb = _.map(color.match(/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/i).slice(1), function(num){
             return parseInt(num, 16)
        });
    } else {
        return 'Invalid color type.'
    };
    var result = _.map(rgb, function(item) { return Math.floor(value*item) });
    return 'rgb('+result.join(',')+')';
}
· · · ◊ ◊ ◊ · · ·

Leave a Reply