Displaying below is a simple JavaScript function without any dependencies, while only the testing function utilizes jQuery for functionality.
A collection of colors is stored in an array of objects since you mentioned a specific requirement to match around 10 predefined colors. The majority of the code focuses on visual representation.
The findClosestColorHex
function accepts a hex value such as '#FF0000', whereas findClosestColorRGB
takes three separate integers representing R, G, and B values. Both functions expect the color table as a parameter, allowing for easy customization if necessary, yet can be hardcoded if usage with a fixed set of colors is preferred.
In certain scenarios, the outcome may not be exact due to the limited palette defined in the color array comprising only 16 fundamental shades.
var ColorTable = [
{name:'black', hex: '#000000'},
{name:'silver', hex: '#C0C0C0'},
{name:'gray', hex: '#808080'},
...
{name:'aqua', hex: '#00FFFF'}
];
...
.color-field {
display: inline-block;
width: 200px;
height: 50px;
background-color: #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
R: <input id="slider_r" type="range" min="0" max="255" step="0"/> <input type=text id="value_r" value='0'><br>
G: <input id="slider_g" type="range" min="0" max="255" step="0"/> <input type=text id="value_g" value='0'><br>
B: <input id="slider_b" type="range" min="0" max="255" step="0"/> <input type=text id="value_b" value='0'><br>
<br>
Selected: <span id='selected_color' class='color-field'> </span><br>
Matched: <span id='matched_color' class='color-field'> </span><span id="color_name"> </span>