David G
David G

Reputation: 96790

Is there a way to convert word colors ("red", "blue", "green") into #123456 values?

I've been stuck on this for a while. I keep trying to compare colors for elements but even if the colors are the same, the values representing them are not. One is #000 and the other is "black". How do I take "black" and turn it into #000. With that said, how do I take any word color and turn it into a number?

Upvotes: 1

Views: 658

Answers (4)

Pointy
Pointy

Reputation: 413692

If you set a CSS color property to your color string and then get the property back, most (at least some) modern browsers will give you a "normalized" color string. Firefox seems to like the "rgb(n, n, n)" notation.

edit — @Andy E notes that this doesn't work in too many browsers.

Upvotes: 1

Andy E
Andy E

Reputation: 344517

I'm not sure it is possible x-browser without a predefined list of colours. It's simple enough in browsers supporting window.getComputedStyle():

function getColorFromName(name) {
    var rgb,
        tmp = document.body.appendChild(document.createElement("div"));

    tmp.style.backgroundColor = name;
    rgb = window.getComputedStyle(div, null);
    //-> returns format "rgb(r, g, b)", which can be parsed and converted to hex
}

For browsers not supporting this, the only option you have is to use an object map and define the values yourself:

var colours = {
    aliceblue:      "#F0F8FF",
    antiquewhite:   "#FAEBD7",
    aqua:           "#00FFFF"
    //...etc
}

// and lookup
alert(colours[document.getElementById("div").style.backgroundColor.toLowerCase()]);

A full list of colours supported in CSS3 is available from http://www.w3.org/TR/css3-color/#svg-color.

Of course, the downside to the list method is that lists need to be maintained if the specification changes, so you might want to incorporate both methods - ie if getComputedStyle() is available, use it else fall back to the list. This ensures compatibility for both older browsers and newer browsers without ever needing to update the list.

Upvotes: 1

nonouco
nonouco

Reputation: 1170

Since you are using javascript you can use a "javaScript associative array" and have the assosiation "colorName <-> colorCode" you need.

You can find all the official color names here: http://www.w3schools.com/cssref/css_colornames.asp

here is some code:

var colors= new Array();
colors["black"] = "#000";
colors["AliceBlue"] = "#F0F8FF";
colors["AntiqueWhite"] = "#FAEBD7";

var mycolor = 'black'
alert('the code of '+mycolor +' is:'+colors[mycolor]);

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

I've seen this question asked in the past and i think you can find a good script here.

The script is from a great programmer in javasscript and, well, actually he does a word look up, there is no other way to do it i think.

Upvotes: 6

Related Questions