Tips, Tutorials

jQuery Color Picker

January 27, 2009 • By

Gone are the days of having to manually enter in hex codes to specify colors: with jQuery UI’s color picker, you can make your web application pick colors as smoothly as you would in desktop applications like Photoshop. When coupled with the visual appeal and functional benefit of color pickers, the ease of using jQuery UI’s gadget is something that’s hard to pass up.

The Example

Getting Started

The color picker can be downloaded from the jQuery UI download page and then included in our page using the <script> tag. Furthermore, the CSS file that is inside the default theme folder should be included, as should all of the images. There are a fair number of items to include for the color picker, but they are needed to form the interface. These should be placed within your <head> tags:

<link rel="stylesheet" href="ui.colorpicker.css"/>
<script language="JavaScript" src="jQuery.js"></script>
<script language="JavaScript" src="jQuery.colorpicker.js"></script>

All we need to do to make use of the color picker gadget is to call the .colorpicker function on a form field or div to begin:

$('#picker').colorpicker({ flat: true });

By attaching the picker to just a div and specifying the flat parameter to be true, you should see the following:

It is worth an honorary mention that the eventName parameter can be set to the name of the event that should trigger the opening of the color picker. That is, you can specify to have the color picker show up on mouseover instead of the standard click.

Wrapping Things Up

By placing the hex code into the text field at the end, we ensure that we can access the hex code from normal forms and JavaScript alike. By using standard convention with the form handling, this method also ensures that there is a safe fallback to users who have JavaScript disabled. The following is the completed example using the hide event to return the hex code, and then making use of that hex code to style the page.

Tutorial kindly written by Nathan Wong