Recently I was tasked with creating a form that allowed the user to specify a color selection from a limited number of options. There are numerous scripts that display a popup color selection on the web, but I needed one that was limited to just a few colors. So I wrote a script that makes all text inputs in a form with the class name of “color” display a simple color selection box. Here’s what it looks like in action:
Implementation
Download and store the JavaScript and CSS:
Simple Color Selector (.zip)
Simple Color Selector (.tar.gz)
Then add the following references to your page:
<link rel="stylesheet" href="/lib/styles/colorPicker.css" type="text/css" media="screen" />
<script type="text/javascript" src="/lib/js/colorPicker.js"></script>
Usage
The script creates the color table and assigns click events dynamically, so all you have to do is include the word “color” in text input classes like so:
<input type="text" class="color" />
By default, the script displays the following colors: White (blank), black, grey, red, yellow, and blue. You can easily replace the default colors by adding the following after you reference the main JavaScript file:
<script type="text/javascript">
colorPicker.colors = new Array('', 'black', 'gray', 'red', 'yellow', 'blue', 'teal');
</script>
And that’s it! The user’s selection will be hidden within the text inputs, so upon submission you’ll be able to work with the resulting data. Feel free to modify functionality within the JavaScript file, or style within the CSS file.
