Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get background-color in #000 format and not RGB [duplicate]

Tags:

jquery

rgb

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

like image 499
David Avatar asked Mar 30 '13 08:03

David


1 Answers

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;
}
like image 131
Devang Rathod Avatar answered Sep 20 '22 21:09

Devang Rathod