Wednesday 18 August 2010

Wordpress colorpicker.js

The Wordpress wp_enqueue_script reference page lists Colorpicker as one of the default scripts imstalled, but doesn't offer any clues on how to implement it. The link on that page (currently) points to which has no details on how to use it either.

The best online reference I've found so far is Matt Kruse's JavaScript Toolbox - Color Picker Swatch Popup which suggests you look at which doesn't have any documentation about colorpicker.js. Here's a link to the cached version of the documentation page just in case the source page is taken down:

The javascript file /wp-includes/js/colorpicker.js is minified and browsing it doesn't easily reveal anything. There's a lot more information in /wp-includes/js/ but it's not as straightforward as it could be.

What you need to do:

Include the colorpicker javascript file:
wp_enqueue_script( 'colorpicker');

Create a colorpicker object and hidden div, preferably put this near the end of your page:
var cp = new ColorPicker(); cp.writeDiv();

Set up the input field and picker anchor tag:
Color: <INPUT TYPE="text" id="color2" name="color2" SIZE="20" VALUE=""> <A HREF="#" onClick="jQuery('#color2').each(function(index){,'pick2');return false;});return false;" NAME="pick2" ID="pick2">Pick color</A>

Alternatively, you could also try this approach where you ditch the anchor tag and use some jQuery to handle the rest:

<INPUT TYPE="text" id="color2" name="color2" SIZE="20" VALUE="" class="jColorpicker" >

jQuery(".jColorpicker").bind("click", function(){,jQuery(this).attr(\'name\')); });

This snippet of code is showing it's age and there are better options out there if you need a color picker. The more I try to use it the more I become frustrated with it.

jQuery UI doesn't have a native one (yet) but I am guessing that will come in time. For now, probably the best candidate is the jQuery plugin jPicker from Digital Magic Productions.