This question already has answers here:
Closed 7 years ago.
With this code, I get the RGB color of any TD in my table :
alert($(this).css('background-color'));
the result is :
rgb(0, 255, 0)
Is it possible with jquery to obtain the #000 format or have I to use a function to transform the rgb in #000 format ?
Thanks in advance for your help
Try
var color = '';
$('div').click(function() {
var hexcolor = $(this).css('backgroundColor');
hexc(hexcolor);
alert(color);
});
function hexc(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
delete(parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
return color;
}
Here's a function I wrote earlier, it does the job for me, and has no looping.
function rgbToHex(total) {
var total = total.toString().split(',');
var r = total[0].substring(4);
var g = total[1].substring(1);
var b = total[2].substring(1,total[2].length-1);
return ("#"+checkNumber((r*1).toString(16))+checkNumber((g*1).toString(16))+checkNumber((b*1).toString(16))).toUpperCase();
}
function checkNumber(i){
i = i.toString();
if (i.length == 1) return '0'+i;
else return i;
}
JSFIDDLE