2

I am trying to get the background color of an element:

var bgcolor = $('.myclass').first().css('background-color')

and trying to convert this to hex

function rgbhex(color) {
    return "#" + $.map(color.match(/\b(\d+)\b/g), function (digit) {
               return ('0' + parseInt(digit).toString(16)).slice(-2);
    }).join('');
}

but the problem is, I am getting in FireFox "transparent" for bgcolor, where rgbhex() is failing with error:

TypeError: elems is null

but in chrome, I am getting rgba(0, 0, 0, 0) and rgbhex() is working for this.

how can I get the css color in crossbrowser format and convert it to hex?

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

0

Surely you're going to have to handle situations where the colour is set to a none rgba value?

Browsers are never going to handle this sort of thing perfectly consistently so I think the problem is that you're assuming an rbga value everytime, leaving the code brittle. Even if you use getComputedStyle(), which will be more consistent in good browsers than css() (which just gets the value directly) you'll still want to handle the edge cases.

I'd do this:

if ('transparent' === bgcolor) {
  hex = '#000';
} else {
  // work magic here
}

But, you're going to hit other examples in other contexts where the browsers are collectively inconsistent, so perhaps a case statement with a default of black, or white, would be a better solution.

Toni Leigh
  • 4,830
  • 3
  • 22
  • 36