LakTEK A Sri Lankan, A Rubyist and A Web Dude

Posted
27 October 2008 @ 2pm

Tagged
, , , ,

Really Simple Color Picker in jQuery

Recently, I needed to use a color picker with predefined color palette for my work. Thanks to many enthusiastic developers, there are several popular, sophisticated color pickers already exist for jQuery. However, most of these plugins looks complex as if they are made to be used in a online image editor. They are overwhelming for simple usage and less flexible for customization. So I had to write my own simple color picker from the scratch.

Usage of color picker is very straightforward. Users can either pick a color from the predefined color palette or enter hexadecimal value for a custom color. Compared to other plugins, it is very lightweight (it’s only 5KB without compressing) and obtrusive to use. It doesn’t require any dependencies apart from jQuery core and uses simple HTML/CSS for presentation.  You have the ability to easily customize the default color palette by adding more colors or replacing the palette with completely different set of colors.

Want to try?

If you want to see a demo before trying out by yourself, here is a simple demo of the plugin.

Download Color Picker via GitHub

Usage

Color Picker requires jQuery 1.2.6 or higher. So make sure to load it before Color Picker (there’s no other dependencies!).
For default styles of the color picker load the CSS file that comes with the plugin.

<script src="jquery.min.js" type="text/javascript"><!--mce:0--></script>
<script src="jquery.colorPicker.js" type="text/javascript"><!--mce:1--></script>

Add a text field to take the color input.

<div><label for="color1">Color 1</label>
<input id="color1" name="color1" type="text" value="#333399" /></div>

Then call ‘colorPicker’ method on the text field when document loads.

  jQuery(document).ready(function($) {
    $('#color1').colorPicker();
  }

Your favorite colors are missing? Just add them to the palette

  //use this method to add new colors to palette
  $.fn.colorPicker.addColors(['000', '000', 'fff', 'fff']);

Or completely change the color palette as you need…

  $.fn.colorPicker.defaultColors = ['000', '000', 'fff', 'fff'];

That’s all you have to do!

Future Improvements

This is only the initial release of Color Picker. There may be wild browser bugs or you may find smarter ways to improve the functionality of the plugin. I’m open to all your suggestions and complaints. Leave a comment here or contact me directly.

Further, the code of the plugin is available via GitHub, so if you feel like forking it and playing with it please do!

Update

Plugin now supports all major browsers including IE6! (Thanks muser for the patch)

Update #2 (October 14, 2009)

Color picker will automatically update it’s color when the value of the input field is changed externally. (Thanks John for initially identifying the issue and Sam Bessey for pushing me on to this change :) )


  • Nice code. Thanks!
  • Joel
    This is exactly what I was looking for! Thank you for saving me a lot of time writing my own. Much appreciated!
  • Bryan
    I have the following use case:

    After the color picker has been opened and the user enters a hexadecimal value and presses enter or clicks on the desired color I would like to persist that to the database. However, the changeColor method is not exposed. Any thoughts on a good way to do this so that updates/bug fixes are easy to manage?
  • Brilliant bit of code. Saved me a lot of time. Thanks for the effort, most appreciated!
  • Jeff Armbruster
    I would like to call colorPicker directly from an input that is created dynamically.

    onclick="colorPicker()" doesn't work, $.colorPicker doesn't work, $.fn.colorPicker doesn't work.

    Any suggestions?
  • I haven't got a chance to touch this recently. I'll have a look in weekend and get back to you.
  • Francesc
    Hi,
    Thanks for the nice work.

    Similar problem here.
    I create dynamically a table and each row has an input text.
    I can attach to all rows the colorPicker using their class name:
    $('.colorPicker').colorPicker();
    However, color picker doesn't show any color. It doesn't read the value of the input.
    If I change the color using the color picker, it doesn't change the value of the input either.
    When I am trying to get it ( $('#inputx').val(); ), still shows the original value.

    Any suggestion?

    Francesc
  • Sjcunningham
    please help! I have to same issue - I dynamically insert an html form using jquery - then want to apply the color picker. But I will not seem to initialise on the dynamically created form field? (However using the same approach I can get it to initialise on a static input in the original html source) -

    But great plugin - nice work
  • Hello, I am considering the use of this plugin in a project.
    I read above someone asking a small feature, adding a remove option to the collorpicker besides adding it.
    It it planned ?

    thanks
  • fabrice.regnier
    Hi ;)

    First, thanx for your nice work ;)

    Could you give a small code example where you can change on the fly the value color of a colorpicker item (providing by the Update #2 (October 14, 2009).
    My $("#color1").val("#FFFFFF") doesn't change anything

    best regards,

    f.
  • fabrice.regnier
    shame on me:

    $("#color1").val("#FFFFFF").change();

    great plugin, though ;)

    f.
  • conradc
    hi, firstly just like to say thankyou for a very nice colorpicker plugin!

    on my page i have several colorpickers, and i would like to disable certain colors in the other pickers once a color has been selected. and obviously enable the color if the selected color is changed (and then that color being now disabled). im quite unsure how to go about doing this or where to start exactly, is anyone able to perhaps help me out or guide me in the right direction?

    thanks again,
    conrad
  • Matthias
    Hi,
    thanks for this!
    I needed a callback function for changing the color value in a database, so I expanded this VERY nice plugin with the following code:

    at the beginning:
    [code]
    $.fn.colorPicker = function(options){
    if(this.length > 0) {
    buildSelector();
    }
    var defaults = {
    onColorChange : function(){}
    };
    settings = $.extend({}, defaults, options);
    return this.each(function(i) {
    buildPicker(this);
    });
    };
    [/code]

    later in the "changeColor" function:
    [code]
    [...]
    settings.onColorChange.call(selectorOwner, selectedValue, $(selectorOwner).prev("input").attr("id"));
    hideSelector();
    [/code]

    now I´m able the call the plugin with:
    $("#id_of_your_input").colorPicker({
    onColorChange: function(e, ad){
    //do stuff like $.post("action/id:ad/") with the "e"
    }
    });
  • Denis
    Hi. Thanks for the plugin.
    It have some problem while element value changes to empty. To avoid if just add the string
    selectedValue = selectedValue?selectedValue:'transparent';
    in change() event.
  • Nadine
    Hi there,
    this colorpicker is really great.
    I only have the problem, that i need more than one on one page with different palettes.. would this be possible somehow?
  • Sam Bessey
    Wow you really are a man of your word- thank you very much for putting the effort in here... This plugin is really awesome now!
  • nice work machan. will try it on next project. :)
  • Hi Sam,

    Sorry for overlooking this plugin for sometime. I'm little bit busy with other work.

    Anyway, have made the change merged into the plugin. Now Color picker should automatically change the color, when the value of input field is changed from an external event.
  • Sam Bessey
    Guys,

    I have posted twice here now. Can someone PLEASE help me, as I am wasting hours and hours on trying to get this working as I want!

    Can anyone expand on the code written by John
    7 November 2008 @ 9pm? I cannot get it to work.

    (This is to get something else to get the colourpicker background colour to change)

    Thanks
  • Greetings, I am using this plugin in a project. It works nicely however an option to remove the colorpicker besides adding it would be nice. For now i am removing the div created with the picker but i am still unable to make it work again. best regards
  • Many thanx, this is what I was looking for a simple color picker!!!
  • cambazz
    can we have the color picker always on? without the input box?
    best regards,
    -c.b.
  • Great plugin! Added some code to my version that allows me to still display the input box as well as the color selector control to the right. I made the display input as an option so the default behavior remains unless you call the following:

    $.fn.colorPicker.displayInput(true);

    Please email me if you would like me to send you the source to be added to the plugin. Email angelo [at] mandato.{dot}.com

    Thanks again!
  • Sam Bessey
    Hi

    Can anyone expand on the code written by John
    7 November 2008 @ 9pm?

    I can't get it to work

    Thanks
  • mcpiper
    Hi Lakshan, great plugin, it's exactly what I was looking for. I'm new at jquery and could use some tips to make it perfect for my needs.
    I have three color pickers on one page (just as in your demo), and I need to change the default colors depending on which element is chosen. Thanks for any advice.
  • element
    Thanks for this great plugin, it was just what I was looking for!
  • Muser & TaeWoo: Thanks for spotting the bug. Fixed it.
  • Muser
    Sorry...line 93 (I had deleted the 'alert' just before that)
  • Muser
    I've found this bug on line 91:

    hexColor = $(selectorOwner).next("input").val();

    should be:

    hexColor = $(selectorOwner).prev("input").val();
  • TaeWoo
    Thanks Lakshan.
    IS there a debug mode or something? I constantly get into scenarios where the color picker opens up but does not close once clicked...
  • TaeWoo >> You could get the actual selected color by the value of assoicated text field.
  • TaeWoo
    How do you get the actual selected color in hex?
  • Muser >> I will try to put some time into the issue you mentioned above.

    BTW, it seems GitHub is having some problems right now. Anyway you should be able to download the arrow.gif from Github.
  • Muser
    P.S.: The download from github is missing the gif - does it take a while to update?
  • Muser
    No worries...thanks for the updates. The plugin is really handy and efficient.

    There is one other minor change I'd consider. I've got some color pickers appearing in a dialog that can be moved/resized. It would be nice to detect if div#color_chooser exceeds the right/bottom bounds of the screeen - if so, the div could be displayed above and/or to the left of the picker, instead of the default bottom-right placement.

    That's just a nice-to-have though...I might try my hand at it sometime if I have time, and if you or someone else hasn't got to it first.
  • Muser,

    First of all sorry for not being able to keep to my word. And thank you for coming up with this. Coincidently, I also just completed making the plugin compatible with IE6 over this weekend. I was about to push the new release. Anyway, you beat me in it..

    Thanks again for your wonderful contribution. Really appreciate it!
  • Muser
    Note in my previous post the spot that says to add the text ' ' is supposed to say add the text '&nbsp;'
  • Muser
    Seems that a few days is turning into a month...in the meantime, I need this to work. So I actually figured out and hacked up a solution to the problem(s). I've pasted my fixed code here: http://pastebin.com/m428aee1c. Read on for a description of what needed to be changed.

    First, IE6 can't use transparent PNGs...convert the arrow.png image to a gif, and change the css accordingly. There is a png transparency hack for IE6, but it's not really worth the trouble in this case.

    Second, IE6 is apparently unable to use element IDs or class names that start with an underscore. So remove those wherever they occur in the css/js (for example, change any use of '_color_selector' to 'color_selector' in the js, and change 'div#_color_selector' to 'div#color_selector' in the css...and so on).

    Finally, a couple fixes are needed to make sure the height of the colour picker/swatch divs are sized to the correct height. First, you need to add the text ' ' (no quotes) to the color_picker and color_swatch divs in the js code (lines 20 and 38 in my copy from the github repo). This makes IE6 respect the line-height CSS property - now you need to add 'line-height:16px' and 'line-height:12px' to the css classes for color_picker and color_swatch.

    That's it...it should now work in IE6 (it does for me at least).
  • kemal
    Lakshan,

    I do appreciate your color control and I did use it in my test project but before going production, I wanted to ask you whether you could manage to resolve the above issues.

    when are you planning to release the next version?
  • Muser
    Any ideas/progress on fixes for IE6? I know it's an outdated browser, but my target audience includes many dial-up users...who generally do not update their browsers (or try alternatives), but also benefit from the compact code that your plugin uses.
  • @kemal I will look into this issue. Actually I'm working on the next release of the plugin which will be released in few days.
  • kemal
    the controls textbox cannot be edited when it is used inside a modal (jquery.modal plugin)

    any workaround to this?
  • Nice plugin.

    I just wrote a Django snippet to use your color picker simply using a Django model field: http://www.djangosnippets.org/snippets/1261/

    Cheers,
    Fabian
  • Amazing plugin, love the simplicity.

    Is there any news on a fix for IE6?

    Good work

    Chris
  • dpdexter
    Very cool plugin! Simplicity is awesome.....
  • This is just what I needed! This will save me a lot of head ache..

    Thank you
  • neoswf
    Amigo- I would appreciate if u could help me fixing it to IE6. please email me any solution to this matter. I would send u a big thanks from Brazil :) neoswf(at)gmail-Dot-com
  • neoswf
    Hey
    Thanks for the plugin, but it doesn't work on IE6... How to fix it?
  • Hi, this picker works great.. after checking out a few jquery color pickers I decided to use this one because it is light and it works as it should. Best regards, Miha
  • Hey Lakshan, I like it!

    I had the reverse problem of yguaratã - I had outside forces changing the hidden input and watched the swatch to update when something changed the hidden input.

    I made a quick hack to

    (1) Pass the input as an argument to the `buildSelector` function from `colorPicker`:

    $.fn.colorPicker = function(){
    if(this.length > 0) buildSelector(this);
    return this.each(function(i) { buildPicker(this)});
    };


    (2) Add a change listener to the input at the end of the `buildSelector` function to update the swatch as things change.


    $(input).change(function() {
    selectedValue = toHex($(input).val());
    $(this).prev(".color_picker").css("background-color", selectedValue);
    });

    Now whenever the input is changed it updates the current color swatch!

    Thanks!
  • Love the simplicity but this pluggin has many issues with IE6. To many to list here.
  • Hi yguaratã,

    Thank you very much for the contribution. It's a handy addition. I committed your change to plugin's github repo.
  • HI, good job man!!

    I was tring to use change event facilities from jquery with your plugin, but without success. I wanted something that trigged a function when a changed the color.

    Thus i changed the changeColor function from your code to the following (just added .change() call at the end):

    changeColor = function(value){
    if(selectedValue = toHex(value)){
    $(selectorOwner).css("background-color", selectedValue);
    $(selectorOwner).next("input").val(selectedValue);

    //close the selector
    hideSelector();
    $(selectorOwner).next("input").change();
    }
    };

    Maybe it is useful for someone else.

    thank you!
  • Great work! :)
  • This is good work man. I will try it it our in my next JQuery project.
blog comments powered by Disqus