2

Using JSColor, after the user picks a color, how do I get the "hex"?

$("input#colorpicker").css('background-color') => this returns background-color: rgb(107, 132, 255);

But not a hex.

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

3 Answers3

3

I assume that jQuery.css returns the value that was set. Try the following function to convert RGB to HEX:

function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);

    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

colorToHex('rgb(120, 120, 240)')
Alex Dn
  • 5,465
  • 7
  • 41
  • 79
1

Actually upto an extent this depends on browser that it returns in rgb or hex, anyway check out this threads there are nice discussions about it and there are many solutions as well.

Background-color hex to JavaScript variable

and

How to get hex color value rather than RGB value?

and

Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

and

jquery css color value returns RGB?

Community
  • 1
  • 1
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
0

There is onchange event available:

$("input#colorpicker").change(function() {
    console.log(this.color);
});
dfsq
  • 191,768
  • 25
  • 236
  • 258