I have an application where the user can type in a color name, say blue
, once he/she has done that, a div will turn into that color.
The code is pretty simple at the moment:
<div class="colorBox" style="background-color: <%= color.name %>;">
</div>
Is it possible to check whether or not that particular color exists? At the moment I can only think of one solution:
Loop through a list of color names, like this one, but isn't there a more elegant way? E.g
CSS.exists("blue")
=> true
Also, I don't want the user to enter a color hex.
$(...).css('background-color')
) it will return an RGB
format color even if no color was setted on that elementundefined
...so if you change a color with a fake name since it wouldn't set for that property, the property will hold previous valid color (if it has one) and when you want to check that you will check an old valid color name not a new invalid one.
This should work. Call if after the user sets the color;
function isColorValid(element, value) {
return element && element.style.backgroundColor === val;
}
EDIT: jsFiddle
The Color gem/Color::CSS is what you want:
Returns the RGB colour for name or nil if the name is not valid.
From your question, it appears that you would like to do check on the server itself. However, recognition of colors is a browser specific behavior and hence a round trip to browser would be required.
Following is a way. I would be interested in seeing if someone has something more elegant. We assume you are using jquery.
Put a '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 fact that the browser would simply ignore a color value if it cannot recognize it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With