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.

About

Not Just a Hat Rack (NJHR) focuses on best practice solutions for problems you’ll encounter during a typical site build. There’s an emphasis on new technology when possible (HTML5, CSS3, etc.), but all suggested solutions will work cross-browser, quickly and efficiently. more »

I'm Andrew Church, an aspiring web developer currently living and working in Washington, DC. I’ve been employed as a professional developer since 2004, when I graduated with a degree in Information Sciences & Technology from Penn State University. I'm particularly interested in front-end web development technologies (HTML, CSS, JavaScript), but I do have experience with the entire site build process. « less

Tweets

Delicious