An easy way to add a color picker to your website

crowded_crayon_colors[1]

In my work, I have often had to develop web-based tools that allow the user to create their own content for printing, web, or mobile. This almost always involves letting them choose colors for their text, background, etc.

As you probably know, colors on the web are usually represented as a 24-bit number that contains the right mix of red, green, and blue that’s needed to display the color you want. Those 24 bits are most often expressed as a six-digit hexadecimal number such as #483D8B.

In the earlier days, websites would simply ask the user to enter that six-digit number in a text input box in order to select the color they want. Not very user-friendly, right? To improve usability, you could provide a list of colors, and the user would click on the desired one. However, that limits the choice of available colors, and it is more difficult to code.

Different Javascript-based solutions have been developed in order to provide a good color picker, but in my opinion all of them had some limitations and took extra time and effort to implement.

HTML5 includes many additional user interface elements that allow you to enter data much more easily. One of them is the “color” input type. It solves our color problem completely — in an HTML form, you could add a color input with a single line of code. The browser would assist the user in picking a color, and the back-end application would get the hexadecimal code that computers can work with. The code for the input element is as simple as that:


Then the browser would natively provide all the UI tools needed to select a color:

input-type-color[1]

The only problem is that, right now, the color input is supported by a very limited set of web browsers. But recently, I was fortunate enough to find Spectrum, an awesome jQuery plugin that fills in the gap. It will automatically find color inputs on your page, and if your browser does not support them natively, then it will replace them with an easy to use Javascript-based color picker element. It can work with zero configuration, and the minimum setup requires only two extra lines of code:



For more advanced tweaking, Spectrum provides many additional options as well. Among the available solutions, I would highly recommend it to my fellow web developers. For demos, downloads, and documentation you can go to the plugin’s page.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.