Tuesday, October 16, 2012

Color Made Easy with the jQuery Color Plugin

The jQuery Color Plugin powers the color animation in jQuery UI.  In general, you don't even realize its there.  There's only a small reference to it in the API docs for jQuery UI.  However, the plugin is a self-contained library full of useful features that you can leverage when trying to dynamically manipulate colors.

The GitHub home has a good writeup on the plugin so I won't regurgitate what's already been said.  However, I was working on something that required me to find a darker version of the color a user selected so I could create a highlight (or low-light) effect.  Without the Color plugin, I'd have to do some work to find a way to darken the color.  However, with the plugin, it was as easy as retrieving a color object, calling lightness(), and then grabbing the new color value.

In my sandbox, I tested this concept on several colors.  I passed in color names, hash color values, and RGB/HSL space values to the plugin, stepped through the lightness values, and rendered those colors into little color swatches with their corresponding RGB/HSL values.

As a final test, I used a color picker widget to pick the main color and then calculate a highlight color that would contrast nicely with the main color.  I used that calculated color as the border to my div.  Depending on the desired contrast, you can adjust the math used to find the new lightness value.

Overall, the jQuery Color plugin is a nice utility that can save you a lot of extra work.  If you need to perform extensive color operations in your code, this might be a good library to check out.  If you're already using jQuery UI, then its already included in your site and you can leverage its goodness now.