bakedproject.com Blog Not just another WordPress weblog

10Mar/111

Adding ColorPicker jQuery plugin to a WordPress plugin admin panel

I was working on a WordPress plugin and needed to add a color picking ability for the admin panel. After doing some research I ended up with a few choices but decided to go with ColorPicker jQuery plugin. Installation required nothing extraordinary, just made changes to the CSS file. I like to keep my resources in separate folders so instead of having everything under images folder, I have them under "images/colorpicker" folder.

The WP plugin I am built has the ability to set default color for the color picker from the plugin settings page. The preset color would load during the colorpicker initial load. I selected "#faaf40" as the default color but started to have a really weird error! My form would not submit with the set color. On Safari I wasn't getting any feedback, but on Chrome I could see a message saying

Please shorten the text to 3 characters or less (you are currently using 17 characters).

Initially I did not even notice this, I thought something from the jQuery side of things were failing on form submit. I looked into the colorpicker code and realized the RGB/HSB text fields are limited to 3 characters. I figured out the conversion of the hex "#faaf40" was causing the issue. So I slightly modified the "fillHSBFields" assignment(starting on line 35)

1
2
3
4
5
6
fillHSBFields = function  (hsb, cal) {
	$(cal).data('colorpicker').fields
		.eq(4).val(Math.round(hsb.h)).end()
		.eq(5).val(Math.round(hsb.s)).end()
		.eq(6).val(Math.round(hsb.b)).end();
}

I simply rounded the calculated HSB values!

Comments (1) Trackbacks (0)
  1. The calculation is a bit off cause of rounding it, but seems ok!


Leave a comment

(required)

No trackbacks yet.