This can be a difficult problem. After several attempts, I came up with a pretty clean solution. Let browswer do the work for you.
Step 1: Create a div with a border style of none. A div can be placed off-screen or it can be any div on your page that does not use borders.
Step 2. Set the border color to an empty string. The code might look something like this:
e=document.getElementbyId('mydiv'); e.style.borderColor="";
Step 3. Set a border color for a color that you are not sure about.
e.style.borderColor=testcol;
Step 4: Check if the color has really changed. If testcol is invalid, there will be no change.
col2=e.style.borderColor; if(col2.length==0) {alert("Bad Color!");}
Step 5: Clean yourself by setting the color back to an empty string.
e.style.borderColor="";
Div:
<div id="mydiv" style="border-style:none; position:absolute; left:-9999px; top:-9999px;"></div>
Now the JavaScript function:
function GoodColor(color) { var color2=""; var result=true; var e=document.getElementById('mydiv'); e.style.borderColor=""; e.style.borderColor=color; color2=e.style.borderColor; if (color2.length==0){result=false;} e.style.borderColor=""; return result; }
In this case, the function returns a true / false answer to the question, another option is to return the correct color value. Original color value, from borderColor value or empty string instead of invalid colors.
Terry Prothero Jan 25 '13 at 23:52 2013-01-25 23:52
source share