Skip to main content
new code that works.
Source Link
DuckMaestro
  • 16k
  • 11
  • 71
  • 87

Updated informationYou'll need to rely on --getComputedStyle(...).

As of jQuery v1.4.4, the following will actually perform what you need:Example of using getComputedStyle:

var hexColor = $('<div></div>') .css('background-color', namedColor) .css('background-color'); 
function convertToHexColor(englishColor) { // create a temporary div. var div = $('<div></div>').appendTo("body").css('background-color', englishColor); var computedStyle = window.getComputedStyle(div[0]); // get computed color. var computedColor = computedStyle.backgroundColor; // cleanup temporary div. div.remove(); // done. return computedColor; // The above returns "rgb(R, G, B)" on IE9/Chrome20/Firefox13. }; 

Simple!And to convert "rgb(R, G, B)" to #RRGGBB you can use:

function convertRGBDecimalToHex(rgb) { var regex = /rgb *\( *([0-9]{1,3}) *, *([0-9]{1,3}) *, *([0-9]{1,3}) *\)/; var values = regex.exec(rgb); if(values.length != 4) { return rgb; // fall back to what was given. } var r = Math.round(parseFloat(values[1])); var g = Math.round(parseFloat(values[2])); var b = Math.round(parseFloat(values[3])); return "#" + (r + 0x10000).toString(16).substring(3).toUpperCase() + (g + 0x10000).toString(16).substring(3).toUpperCase() + (b + 0x10000).toString(16).substring(3).toUpperCase(); } 

Updated information --

As of jQuery v1.4.4, the following will actually perform what you need:

var hexColor = $('<div></div>') .css('background-color', namedColor) .css('background-color'); 

Simple!

You'll need to rely on getComputedStyle(...).

Example of using getComputedStyle:

function convertToHexColor(englishColor) { // create a temporary div. var div = $('<div></div>').appendTo("body").css('background-color', englishColor); var computedStyle = window.getComputedStyle(div[0]); // get computed color. var computedColor = computedStyle.backgroundColor; // cleanup temporary div. div.remove(); // done. return computedColor; // The above returns "rgb(R, G, B)" on IE9/Chrome20/Firefox13. }; 

And to convert "rgb(R, G, B)" to #RRGGBB you can use:

function convertRGBDecimalToHex(rgb) { var regex = /rgb *\( *([0-9]{1,3}) *, *([0-9]{1,3}) *, *([0-9]{1,3}) *\)/; var values = regex.exec(rgb); if(values.length != 4) { return rgb; // fall back to what was given. } var r = Math.round(parseFloat(values[1])); var g = Math.round(parseFloat(values[2])); var b = Math.round(parseFloat(values[3])); return "#" + (r + 0x10000).toString(16).substring(3).toUpperCase() + (g + 0x10000).toString(16).substring(3).toUpperCase() + (b + 0x10000).toString(16).substring(3).toUpperCase(); } 
Source Link
DuckMaestro
  • 16k
  • 11
  • 71
  • 87

Updated information --

As of jQuery v1.4.4, the following will actually perform what you need:

var hexColor = $('<div></div>') .css('background-color', namedColor) .css('background-color'); 

Simple!