teelou teelou - 2 months ago 7
jQuery Question

How to get the background color code of an element?

How do I get the background-color code of an element?

HTML

<div style="background-color:#f5b405"></div>


jQuery

$(this).css("background-color");


Result

rgb(245, 180, 5)


What I want

#f5b405

Answer

Check example link below and click on the div to get the color value in hex.

var color = '';
$('div').click(function() {
    var x = $(this).css('backgroundColor');
    hexc(x);
    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('');
}

Check working example at http://jsfiddle.net/DCaQb/

Comments