0

I found this code online, but it doesn't do what I want.

function ColorLuminance(hex, lum) {
    // validate hex string
    hex = String(hex).replace(/[^0-9a-f]/gi, '');
    if (hex.length < 6) {
        hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
    }
    lum = lum || 0;
    // convert to decimal and change luminosity
    var rgb = "#", c, i;
    for (i = 0; i < 3; i++) {
        c = parseInt(hex.substr(i*2,2), 16);
        c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
        rgb += ("00"+c).substr(c.length);
    }
    return rgb;
}

So I go ahead and use jQuery to change the background color of the surrounding box (which gets displayed in the Poll results (right-side) background color).

$(".bar-container").each(function() {
    var hexColor = $(this).children(":first").css("background-color");
    var bgColor = ColorLuminance(hexColor, .2);
    $(this).css({"background-color": bgColor});
});

This is used when the document is ready.

What I am trying to do is grab the actual poll color (from the left that is the percentage) and make the overall container color a little bit lighter (but the same basic color). So if the percentage bar is red, it shouldn't make the overall background of the containing bar purple. It should make it a lighter color of red.

The ColorLuminance function isn't working, cause it is changing the color entirely!

How can I modify this function for a lighter color? (preferably percentage-based, which is what the lum parameter is for)

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
Solomon Closson
  • 6,111
  • 14
  • 73
  • 115

1 Answers1

1

To change the luminance of a RGB color I would convert it to HSV colorspace, there you got Hue (the color), Saturation and Value (Brightness). So you are able to only change the brightness.

Then you bring back the color from HSV colorspace to RGB colorspace again.

You can find a HSV javascript inverter here: http://www.javascripter.net/faq/rgb2hsv.htm More information about HSV can be found here: https://en.wikipedia.org/wiki/HSL_and_HSV

Also have a look at Can I force jQuery.css("backgroundColor") returns on hexadecimal format?, colors are always returned already as RGB it seems.

Community
  • 1
  • 1
kaljak
  • 1,263
  • 1
  • 16
  • 34
  • 1
    Ok, wow, didn't realize that it was retuning an rgb value from jQuery's method of grabbing the elements `backgroundColor`. Problem definitely solved now. Thanks :) – Solomon Closson May 17 '13 at 06:00