tags:

views:

1211

answers:

4

Using the following will get the RGB values of a background.

$('#selector').css('backgroundColor');

Anyway to get the Hex value rather than RGB?

Thx

+5  A: 
var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

SOURCE

Kindness,

Dan

Daniel Elliott
+1, You could use Number.toString(16) - at least for each hex digit (or pad with 0 if under 16)
orip
-1. As mentioned by orip, you could use toString(16). Downvoted for other inefficiencies. If you're going to declare hexDigits on every function call, at least do it in rgb2hex's function body (not hex's body), so the array is not redefined 3 times per 1 call to rgb2hex. Also learn to use 'var', so you don't pollute the global scope.
Matt
This works for me, THX
A: 

Here is a cleaner solution, like Matt suggested:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
ErickPetru
A: 

Updated @ErickPetru for rgba compatibility:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

I updated the regex to match the alpha value if defined, but not use it.

Zack Katz