Check if CSS color name exists

I have an application in which a user can enter a color name, say blue, as soon as he does, the div will turn into that color.

Currently the code is pretty simple:

<div class="colorBox" style="background-color: <%= color.name %>;">
</div>

Is it possible to check if this particular color exists? At the moment, I can only think of one solution:

Scroll through the list of color names, like this one , but is there a more elegant way? for instance

CSS.exists("blue")
=> true

Also, I do not want the user to enter hexadecimal color.

+5
source share
3 answers

Colored Stone / Color :: CSS is what you want:

RGB nil, .

+2

. , , ;

function isColorValid(element, value) {
    return element && element.style.backgroundColor === val;
}

EDIT: jsFiddle

+3

From your question, it seems you would like to check on the server itself. However, color recognition is a browser-specific behavior, and therefore you need to get around the trip to the browser.

Here is the way. I would be interested to know if anyone has something more elegant. Suppose you are using jquery.

Put the 'test' div in your html. HTML:

<div id="test"></div>

JS:

function color_exists(color) {
    if (color == 'white') {
        return true;
    }
    $('#test').css('backgroundColor', color);
    if ($('#test').css('backgroundColor') == color) {
        return true;
    } else {
        return false;
    }
}

We rely on the browser to simply ignore the color value if it cannot recognize it.

+1
source

All Articles