How To Allow User To Input A Color (non Hex Or Rbga) For List Customization But Make Sure It's Valid
Just wondering if anyone knows the best way to implement this into code. Is there a method for checking if a string is a valid color? I want to allow the user to click a button to
Solution 1:
You can get the valid color names from the specification CSS Color Module Level 4, set pattern
attribute to RegExp
as string from array delimited by |
for OR
; set required
attribute at input type="text"
element, provide notification to user at adjacent <label>
element whether or not color name is valid.
window.onload = () => {
const cssColor = "https://drafts.csswg.org/css-color/";
const input = document.querySelector("form input[type=text]");
const button = document.querySelector("form input[type=button]");
const img = document.querySelector("form img");
const span = document.querySelector("span");
fetch(cssColor)
.then(response => response.text())
.then(html => {
const parser = newDOMParser();
const doc = parser.parseFromString(html, "text/html");
const colorNames = Array.from(
doc.querySelectorAll(".named-color-table dfn")
, ({textContent}) => textContent
);
console.log(colorNames);
input.pattern = colorNames
.concat(colorNames.map(color => color.toUpperCase())).join("|");
button.addEventListener("click", e => {
if (input.checkValidity())
img.style.backgroundColor = input.value;
});
input.removeAttribute("disabled");
button.removeAttribute("disabled");
span.style.display = "none";
})
}
form * {
padding: 4px;
margin: 4px;
}
img {
border: 1px solid black;
}
#colorName:invalid+[for=colorName]:after {
content: "Invalid color";
color: red;
}
#colorName:valid+[for=colorName]:after {
content: "Valid color";
color: green;
}
<span>loading valid color names..</span><form><inputid="colorName"type="text"requiredpattern=""disabled/><labelfor="colorName"></label><br><inputtype="button"value="click"disabled><br><imgalt="color"width="100px"height="100px"></form>
Solution 2:
Simply by assigning the color to a style attribute, and checking that the attribute has a length > 0 will do the job
e.g. you could do it like this
functiontestColor(color) {
var head = document.head || document.getElementsByTagName('head')[0];
head.style.backgroundColor = ''; // clear it first - which makes it valid
head.style.backgroundColor = color;
return head.style.backgroundColor.length > 0;
}
Tested in firefox, chrome, IE and Edge
Post a Comment for "How To Allow User To Input A Color (non Hex Or Rbga) For List Customization But Make Sure It's Valid"