0

I have hex color code but a jquery object..how can i set background color?

var color = "FF00FF";

if (arr[0] == "True") { 
            $(e.container).closest('td').css('background-color', color);
        }

i tried using this hextorgb function which returns an object. how do i use it in my code?

var color = arr[1];

        var rgbColor = hexToRgb('#' + 'FF00FF');

        if (arr[0] == "True") {
            alert('setting color:'+ rgbColor);
            $(e.container).closest('td').css('background-color', 'rgb(12,3,7)');
        }

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}
Samra
  • 1,815
  • 4
  • 35
  • 71

1 Answers1

1

This hexToRgb method split up color into separate channels. So, as a result you will have three chanels in the object.

var result = {
    r: "128",
    g: "129",
    b: "2"
}

After this you can form new string in format `rgb(${result[0]}, ${result[1], ${result[2]})`, that can be directly set as a background color for DOM element.

Additionally, because you have colors from separate channels, you can modify them buiuld up a new color string.

But if already hav an hex color, it is not clear why do you need such conversions.

Artsiom Miksiuk
  • 3,896
  • 9
  • 33
  • 49