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 http://mattkruse.com/ 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 http://www.javascripttoolbox.com/ 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: http://webcache.googleusercontent.com/search?q=cache:nlxkcPxsepEJ:mattkruse.com/javascript/colorpicker/

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/colorpicker.dev.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:
<SCRIPT LANGUAGE="JavaScript">
var cp = new ColorPicker(); cp.writeDiv();
</SCRIPT>


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){cp.select(this,'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" >

<SCRIPT LANGUAGE="JavaScript">
jQuery(".jColorpicker").bind("click", function(){cp.select(this,jQuery(this).attr(\'name\')); });
</SCRIPT>


Conclusion
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.