0

Possible Duplicate:
Get hex value rather than RGB value using jQuery

I've got a <span> like this:

<span class="colour" style="background:#000000;"></span>

In most browsers, including IE 8, I can get the hex value of the background colour like this:

$('span.colour').attr('style').match(/#[0123456789ABCDEF]{3,6}/gi);

However, in IE 9, $('span.colour').attr('style') returns the following string:

background: rgb(0, 0, 0);

Do I have to convert back to hex in JavaScript, or is there a way to get IE 9 to give me the hex value (i.e. the thing that's actually in the damn HTML) straight from the element?

Community
  • 1
  • 1
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270

2 Answers2

2

You can use the following to convert it (source).

I believe most modern browsers (including chrome) return the rgb and not the hex.

Perhaps you could do a basic match to decide if it was hex or rgb, and then convert the rgb if required.

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

Updated version (supports alpha), as found by Cody O'Dell:

//Function to convert hex format to a rgb color
function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ? "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
Pez Cuckow
  • 14,048
  • 16
  • 80
  • 130
1

i dont think there's a direct function in IE to do that for you. Using a JS is the only way for you to convert the rgb value to the hex code.

here's a function that can convert color values to hex

function toHex(color) {
  var body  = createPopup().document.body,
      range = body.createTextRange();
  body.style.color = color;
  var value = range.queryCommandValue("ForeColor");
  value = ((value & 0x0000ff) << 16) | (value & 0x00ff00) | ((value & 0xff0000) >>> 16);
  value = value.toString(16);
  return "#000000".slice(0, 7 - value.length) + value;
};

you can read more about it over here: http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/

Mevin Babu
  • 2,405
  • 21
  • 34