0

Possible Duplicate:
Javascript function to convert color names to hex codes

Is it possible to retrieve or calculate the hex value that the browser is currently using for a named color? For instance I would like to be able to do something like the following:

(Html):

<div id="container" style="background-color: lightgreen"></div>

(JavaScript):

var container = document.getElementById("container");
var colorAsHex = getHexColor(container, "background-color");

At best I'm hoping for a jQuery solution that I just happen to be missing. At worst I'm fine with browser-specific hacks as long as I can cover the 4 major browsers.

Community
  • 1
  • 1
DuckMaestro
  • 15,232
  • 11
  • 67
  • 85

2 Answers2

3

$('div').css('background-color') seems to be working ... see this example link

Teneff
  • 30,564
  • 13
  • 72
  • 103
  • Wow, interesting. It looks like (from just a brief test) that in jQuery 1.4.2 it returns "green", but in jQuery 1.4.4+ it returns the RGB components. – DuckMaestro Mar 25 '11 at 06:40
1
var namedColor = "lightgreen";
var rgbColor = $("<div></div>").css("background-color", namedColor).css("background-color");
var match = rgbColor.match(/(\d+),\s*(\d+),\s*(\d+)/);
var value = 
    (+match[1] << 16) + 
    (+match[2] << 8) + 
    (+match[3] << 0);
var hexColor = value.toString(16);
while (hexColor.length < 6) {
    hexColor = "0" + hexColor;
}
console.log("#" + hexColor)

Demo here and here.

Salman A
  • 262,204
  • 82
  • 430
  • 521