Digital Magic Productions - jPicker - A jQuery Color Picker Plugin

## jPicker - A jQuery Color Picker Plugin.

jPicker is a fast, lightweight jQuery plugin for including an advanced color picker in your web projects. It has been painstakenly ported from John Dyers' awesome work on his picker using the Prototype framework.
jPicker supports all current browsers and has been extensively tested in Chrome, Firefox, IE5.5+, Safari, and Opera.
If you are updating a current version, you MUST always use the CSS and image files from the download as there may have been changes.
If you are moving from a V1.0.* version, you MUST read the docs below to implement some changes to the Color object returned by the callback functions.
View John Dyer's prototype plugin here.
View jPicker details a docs below.
Check out the source from Google Code.

## jPicker Inline Example

jPicker can be used inline by binding to any block level element.
`jPicker() -- no arguments`

    <script type="text/javascript">
      $(document).ready(
        function()
        {
          $('#Inline').jPicker();
        });
    </script>
    <div id="Inline"></div>

## jPicker Expandable Example

jPicker can also display only a small picker icon that opens a popup for editing.
`jPicker({ window: { expandable: true }})`

    <script type="text/javascript">
      $(document).ready(
        function()
        {
          $('#Expandable').jPicker(
            {
              window:
              {
                expandable: true
              }
            });
        });
    </script>
    <span id="Expandable"></span>

## jPicker Alpha Channel Example

jPicker can also pick colors with alpha (transparency) values.
`jPicker({ window: { expandable: true }})`

    <script type="text/javascript">
      $(document).ready(
        function()
        {
          $('#Alpha').jPicker(
            {
              window:
              {
                expandable: true
              },
              color:
              {
                alphaSupport: true,
                active: new $.jPicker.Color({ ahex: '99330099' })
              }
            });
        });
    </script>
    <span id="Alpha"></span>

## jPicker Binded Example

jPicker can also be binded to an input element.
`jPicker() -- no arguments`

    <script type="text/javascript">
      $(document).ready(
        function()
        {
          $('#Binded').jPicker();
        });
    </script>
    <input id="Binded" type="text" value="e2ddcf" />

## Multiple jPicker Binded Example

jPicker can also be binded to multiple elements at a time.
`jPicker() -- no arguments`

    <script type="text/javascript">
      $(document).ready(
        function()
        {
          $('.Multiple').jPicker();
        });
    </script>
    <input class="Multiple" type="text" value="e2ddcf" /><br />
    <input class="Multiple" type="text" value="" /><br />
    <input class="Multiple" type="text" value="fda0f7" />

## jPicker Callback Functions

Register for callback function to have it interact with your page.
`jPicker([settings, [commitCallback, [liveCallback, [cancelCallback]]]])`

    <script type="text/javascript">
      $(document).ready(
        function()
        {
          var LiveCallbackElement = $('#Live'),
              LiveCallbackButton = $('#LiveButton');  // you don't want it searching this
                                                      // on every live callback!!!
          $('#Callbacks').jPicker(
            {},
            function(color, context)
            {
              var all = color.val('all');
              alert('Color chosen - hex: ' + (all && '#' + all.hex || 'none') +
                ' - alpha: ' + (all && all.a + '%' || 'none'));
              $('#Commit').css(
                {
                  backgroundColor: all && '#' + all.hex || 'transparent'
                }); // prevent IE from throwing exception if hex is empty
            },
            function(color, context)
            {
              if (context == LiveCallbackButton.get(0)) alert('Color set from button');
              var hex = color.val('hex');
              LiveCallbackElement.css(
                {
                  backgroundColor: hex && '#' + hex || 'transparent'
                }); // prevent IE from throwing exception if hex is empty
            },
            function(color, context)
            {
              alert('"Cancel" Button Clicked');
            });
          $('#LiveButton').click(
            function()
            {
              $.jPicker.List[0].color.active.val('hex', 'e2ddcf', this);
            });
        });
    </script>
    <input id="Callbacks" type="text" value="e2ddcf" />
    <span id="Commit" style="background-color: #e2ddcf; display: block; --
              float: left; height: 50px; margin: 10px; width: 50px;"> --
              Commit</span>
    <span id="Live" style="display: block; float: left; height: 50px; --
              margin: 10px; width: 50px;">Live</span>
    <input id="LiveButton" type="button" value="Set To #e2ddcf" />

Commit Live

## jPicker Settings And Colors

Use the "val" method on the active color for interaction with the picker.
`(jQuery).jPicker.List[index]`

    <script type="text/javascript">
      $(document).ready(
        function()
        {
          $('#AlterColors').jPicker();
          $('#GetActiveColor').click(
            function()
            {
              alert($.jPicker.List[0].color.active.val('ahex'));
            });
          $('#GetRG').click(
            function()
            {
              var rg=$.jPicker.List[0].color.active.val('rg');
              alert('red: ' + rg.r + ', green: ' + rg.g);
            });
          $('#SetHue').click(
            function()
            {
              $.jPicker.List[0].color.active.val('h', 133);
            });
          $('#SetValue').click(
            function()
            {
              $.jPicker.List[0].color.active.val('v', 38);
            });
          $('#SetRG').click(
            function()
            {
              $.jPicker.List[0].color.active.val('rg', { r: 213, g: 118 });
            });
        });
    </script>
    <input id="AlterColors" type="text" value="e2ddcf" /><br />
    <input id="GetActiveColor" type="button" value="Get Active Color" /><br />
    <input id="GetRG" type="button" value="Get Red/Green Value" /><br />
    <input id="SetHue" type="button" value="Set Hue To 133" /><br />
    <input id="SetValue" type="button" value="Set Value To 38" /><br />
    <input id="SetRG" type="button" value="Set Red/Green To 213, 118" />

## jPicker Core

jPicker Core function - returns the jQuery object.
`jPicker([settings, [commitCallback, [liveCallback, [cancelCallback]]]])`

## Settings

settings [object]: (with defaults)

    {
      window: // used to define the position of the popup window
              // only useful in binded mode
      {
        title: null, // any title for the jPicker window itself - displays
                     // "Drag Markers To Pick A Color" if left null
        position:
        {
          x: 'screenCenter', // acceptable values "left", "center", "right",
                             // "screenCenter", or relative px value
          y: 'top', // acceptable values "top", "bottom", "center", or relative px
                    // value
        },
        expandable: false, // default to large static picker - set to true to make an
                           // expandable picker (small icon with popup) - set
                           // automatically when binded to input element
        liveUpdate: true, // set false if you want the user to click "OK" before the
                          // binded input box updates values (always "true" for
                          // expandable picker)
        alphaSupport: false, // set to true to enable alpha picking
        alphaPrecision: 0, // set decimal precision for alpha percentage display -
                           // hex codes do not map directly to percentage integers -
                           // range 0-2
        updateInputColor: true // set to false to prevent binded input colors from
                               // changing
      },
      color:
      {
        mode: 'h', // acceptable values "h" (hue), "s" (saturation), "v" (brightness),
                   // "r" (red), "g" (green), "b" (blue), "a" (alpha)
        active: new $.jPicker.Color({ hex: 'ffc000' }), // accepts any declared
                   // jPicker.Color object or hex string WITH OR WITHOUT '#'
        quickList: // this list of quick pick colors - override for a different list
          [
            new $.jPicker.Color({ h: 360, s: 33, v: 100}), // accepts any declared
                   // jPicker.Color object or hex string WITH OR WITHOUT '#'
            new $.jPicker.Color({ h: 360, s: 66, v: 100}),
            (...) // removed for brevity
            new $.jPicker.Color({ h: 330, s: 100, v: 50}),
            new $.jPicker.Color()
          ]
      },
      images
      {
        clientPath: '/jPicker/images/', // Path to image files
        colorMap: // colorMap size and arrow icon
        {
          width: 256, // Map width - don't override unless using a smaller image set
          height: 256, // Map height - don't override unles using a smaller image set
          arrow:
          {
            file: 'mappoint.gif', // Arrow icon image file
            width: 15, // Arrow icon width
            height: 15 // Arrow icon height
          }
        },
        colorBar: // colorBar size and arrow icon
        {
          width: 20, // Bar width - don't override unless using a smaller image set
          height: 256, // Bar height - don't override unless using a smaller image set
          arrow:
          {
            file: 'rangearrows.gif', // Arrow icon image file
            width: 40, // Arrow icon width
            height: 9 // Arrow icon height
          }
        },
        picker: // picker icon and size
        {
          file: 'picker.gif', // Picker icon image file
          width: 25, // Picker width - don't override unless using a smaller image set
          height: 24 // Picker height - don't override unless using a smaller image set
        }
      },
      localization:
      {
        text:
        {
          title: 'Drag Markers To Pick A Color',
          newColor: 'new',
          currentColor: 'current',
          ok: 'OK',
          cancel: 'Cancel'
        },
        tooltips:
        {
          colors:
          {
            newColor: 'New Color - Press “OK” To Commit',
            currentColor: 'Click To Revert To Original Color'
          },
          buttons:
          {
            ok: 'Commit To This Color Selection',
            cancel: 'Cancel And Revert To Original Color'
          },
          hue:
          {
            radio: 'Set To “Hue” Color Mode',
            textbox: 'Enter A “Hue” Value (0-360°)'
          },
          saturation:
          {
            radio: 'Set To “Saturation” Color Mode',
            textbox: 'Enter A “Saturation” Value (0-100%)'
          },
          brightness:
          {
            radio: 'Set To “Brightness” Color Mode',
            textbox: 'Enter A “Brightness” Value (0-100%)'
          },
          red:
          {
            radio: 'Set To “Red” Color Mode',
            textbox: 'Enter A “Red” Value (0-255)'
          },
          green:
          {
            radio: 'Set To “Green” Color Mode',
            textbox: 'Enter A “Green” Value (0-255)'
          },
          blue:
          {
            radio: 'Set To “Blue” Color Mode',
            textbox: 'Enter A “Blue” Value (0-255)'
          },
          alpha:
          {
            radio: 'Set To “Alpha” Color Mode',
            textbox: 'Enter A “Alpha” Value (0-100)'
          },
          hex:
          {
            textbox: 'Enter A “Hex” Color Value (#000000-#ffffff)',
            alpha: 'Enter A “Alpha” Value (#00-#ff)'
          }
        }
      }
    }

## Callback Pattern

`function(jPicker.Color color, object context){...}`

## jPicker List

The list of active jPicker objects.
`(jQuery).jPicker.List[]`

## jPicker Color Class

Definition of the jPicker.Color class.

    (jQuery).jPicker.Color()
    (jQuery).jPicker.Color({ ahex: 'ffffffff' })
    (jQuery).jPicker.Color({ hex: 'ffffff', [a: (0-255)] })
    (jQuery).jPicker.Color({ r: (0-255), g: (0-255), b: (0-255), [a: (0-255)] })
    (jQuery).jPicker.Color({ h: (0-360), s: (0-100), v: (0-100), [a: (0-255)] })
    {
      val: function(name, value, context),
      bind: function(callback) where callback is function(color, [context]),
      unbind: function(callback)
    }

    method "val" usage

    val(name) : get value

      'r':     red         (0-255)
      'g':     green       (0-255)
      'b':     blue        (0-255)
      'a':     alpha       (0-255)
      'h':     hue         (0-360)
      's':     saturation  (0-100)
      'v':     value       (0-100)
      'hex':   hex         (000000-ffffff)
      'ahex':  ahex        (00000000-ffffffff)
      'all':   all         all

      ex. Usage

        val('r'):     (0-255)
        val('h'):     (0-360)
        val('hex'):   (000000-ffffff)
        val('rg'):    { r: (0-255), g: (0-255) }
        val('rgba'):  { r: (0-255), g: (0-255), b: (0-255), a: (0-255) }
        val('hvga'):  { h: (0-255), v: (0-100), g: (0-255), a: (0-255) }
        val('all'):   { r: (0-255), g: (0-255), b: (0-255), a: (0-255), h: (0-360) --
                        s: (0-100), v: (0-100), hex: (000000-ffffff), --
                        ahex: (00000000-ffffffff) }

    val(name, value, [context]) : set value

      'r':     red         (0-255)
      'g':     green       (0-255)
      'b':     blue        (0-255)
      'a':     alpha       (0-255)
      'h':     hue         (0-360)
      's':     saturation  (0-100)
      'v':     value       (0-100)
      'hex':   hex         (000000-ffffff)
      'ahex':  ahex        (00000000-ffffffff)

      ex. Usage

        val('r', (0-255)) || val('r', { r: (0-255) })
        val('h', (0-360)) || val('h', { h: (0-360) })
        val('hex', (000000-ffffff)) || val('hex', { hex: (000000-ffffff) })
        val('rg', { r: (0-255), g: (0-255) })
        val('rgba', { r: (-255), g: (0-255), b: (0-255), a: (0-255) })
        val(null, { r: (0-255), g: (0-255) })
        val('hvga'):  incorrect usage - cannot set hsv AND rgb as they will conflict

## jPicker ColorMethod Utility Class

Static methods for altering and retrieving different color spaces.

    (jQuery).jPicker.ColorMethods.hexToRgba:
        function(hex)
        returns { r: (0-255), g: (0-255), b: (0-255), a: (0-255) }

    (jQuery).jPicker.ColorMethods.validateHex:
        function(hex)
        returns new hex string

    (jQuery).jPicker.ColorMethods.rgbaToHex:
        function({ r: (0-255), g: (0-255), b: (0-255), a: (0-255) })
        returns hex string

    (jQuery).jPicker.ColorMethods.intToHex:
        function(number)
        returns hex string

    (jQuery).jPicker.ColorMethods.hexToInt:
        function(hex)
        return integer

    (jQuery).jPicker.ColorMethods.rgbToHsv:
        function({ r: (0-255), g: (0-255), b: (0-255) })
        returns { h: (0-360), s: (0-100), v: (0-100) }

    (jQuery).jPicker.ColorMethods.hsvToRgb:
        function({ h: (0-360), s: (0-100), v: (0-100) })
        returns { r: (0-255), g: (0-255), b: (0-255) }

## Known Issues

- ### Attaching multiple jPicker objects on a single page will slow performance.

  - jPicker creates a new instance of the picker for every element. Performance will suffer when binding dozens of instances.

## Coming Soon

- - Will consider supporting jQuery ThemeRoller CSS API for theming the UI if demand exists.

## Planned For Future Release

- Move the jPicker object to a single instance that all selection instances point to.
  - This will result in much faster operation and initialization for pages with multiple pickers.
- Add activateCallback option for calling a callback function when the jPicker is activated or its binding is switched to a different picker element.

## Change Log

- ### V1.1.5:

  - Corrected Color object constructor to allow setting of the "alpha" value as per the documentation which previously didn't work.
  - Added support for translucency for quickList colors with checkered background - Only available if "alphaSupport" is enabled.
  - Restricted default color to "alpha" of 255 if "alphaSupport" is disabled - It will now assign an explicit alpha of 255 when disabled.
  - Added new setting variable "alphaPrecision" which indicates the number of decimal points to allow in the alpha percentage display - Now defaults to 0.

- ### V1.1.4:

  - Changed "alpha" range from 0-100 to 0-255 to correct truncating and rounding errors caused by attempting to get an integer percentage that matches a hex value.
  - "alpha" percentage display will now show up to 1 decimal point for more accurate representation of "alpha" value.
  - Color object now accepts "alpha" values in a range of 0-255 and also returns the same when getting the "alpha" value. You will need to run ((alpha * 100) / 255) to retrieve a percentage value.
  - Reworked the table layout and labels to remove the need for the label to reference the radio input box. This reduces injected code and removes the need to generate unique ids on the radio buttons.
  - Transparent/invisible caret on NULL color is now corrected - uses the same caret color as a white color.
  - Setting a binded input value of "" or no value attribute will now create a NULL color on initialization instead of the settings default color.
  - Added a dynamic, invisible "iframe" behind a dialog picker in all browsers that fail jQuery.support.boxModel (currently IE <= 7 Quirks Mode). This prevents "select" box from showing through the picker.

- ### V1.1.3:

  - Now adding popup color pickers to document.body instead of inline with the popup control. This corrects issues with the picker not showing beyond a relative container scope.
  - No longer need to hide popup icon in Internet Explorer for picker elements lower in the DOM than the currently active one since the picker itself is attached to document.body (it is always higher in the DOM now).
  - Popup pickers are now bring-to-front selectable. Clicking on the picker will bring it above all other pickers on the page instead of having to drag one out from underneath another.
  - Corrected jPicker.List/setTimeout bug which allowed an instance to bind to the List in an order other than the order the initialization function was called.
  - Added a updateInputColor option (default true) to allow for a binded input field that does not automatically update its background/text color.

- ### V1.1.2:

  - Reworked the find methods and contexts for element searches. Now using ":first" instead of ".eq(0)" to take advantage of early out searches. Much faster initialization of the picker, on the order of 6 times.
  - Now using setTimeout for calling visual updates. Dramatically improved marker dragging in all browsers. Reduces blocking as re-rendering is internal to the browser and independent of the other javascript still in progress.
  - Marker updates can now cancel a previous valueChanged event when a new mouseMove event comes in. IE8 marker dragging is still slower, much over 5 times faster than it was.
  - Reworked entire quickPick list creation. It now adds up source code and does a single "html" method instead of multiple "append" methods. This is a large part of the speed increase on initialization.
  - The vast majority of all running scripts on both initialization and dragging is now occupied altering the style rules and finding elements (init only) instead of jPicker code.
  - All methods previously called with global context now use the "call" method for using the context of the class running the method. "this" in a callback is now the DOM node (jQuery style) and jPicker instead of "window".
  - Added "effects" section of window settings to allow different show/hide effects and durations.
  - Removed change log and read me from the full source code to separate files (ChangeLog.txt and ReadMe.txt) and an HTML demonstration/documentation page (Example.txt).

- ### V1.1.1:

  - Correct IE exception caused by attempting to set "#transparent" to CSS background-color.

- ### V1.1.0:

  - Reworked nearly the entire plugin including the internal and external event model, bindings, DOM searches, classes, and overall presentation.
  - The Color object now supports a changed event that you can bind to (or just bind to the picker events still included).
  - Event order has been reversed, instead of an change event on the map/bar/text fields updating the display, they now update the Color object which then fires the events that update the display.
  - alphaSupport re-implemented by request - default behavior is off.
  - Hex code now only 6 characters again.
  - Color object can now have its value changed from code, using the "val" method, and it will fire all events necessary to update the display.
  - Removed all "get_*" methods from the color object, instead opting for a single "val" method for getting and setting, more in line with familiar jQuery methods.
  - Better rendering for all IE versions in Quirks mode.

- ### V1.0.13:

  - Updated transparency algorithm for red/green/blue color modes. The algorithm from John Dyers' color picker was close but incorrect. Bar colors are now pixel perfect with the new algorithm.
  - Changed from using "background-position" on the color maps to an element of full height using the "top" attribute for image-map location using "overflow: hidden" to hide overdraw.
  - IE7/8 ignores opacity on elements taller than 4096px. Image maps therefore no longer include a blank first map so the Bar is just under 4096. Blank is now accomplished by setting the "top" setting to below the map display.
  - New colorBar picker image that does not draw outside of the element since the elements now hide overdraw.
  - Added IE5.5/6 support for the picker. This is why it now uses maps of full height and the "top" attribute for map locations.
  - Moved the images in the maps to 4 pixels apart from each other. IE7/8 change the first pixel of the bottom-border of 2px to partially transparent showing a portion of a different color map without this.

- ### V1.0.12:

  - Added minified CSS file.
  - Added IE7/8 Quirks Mode support.
  - Added configurable string constants for all text and tooltips. You can now change the default values for different languages.
  - Privatized the RGBA values in the Color object for better NULL handling. YOU MUST USE THE NEW GET FUNCTIONS TO ACCESS THE COLOR PROPERTIES.
  - Better NULL color handling and an additional "No Color Selected" quick pick color.
  - More consistent behavior across multiple versions of browsers.
  - Added alpha response to the binded color picker icon.
  - Removed "alphaSupport" variable. It is now always supported.

- ### V1.0.11b:

  - Corrected NULL behavior in IE. jQuery was getting an exception when attempting to assign a backgroundColor style of '#'. Now assigns 'transparent' if color is NULL.
  - Can now create new Color object WITH OR WITHOUT the '#' prefix.

- ### V1.0.11:

  - Added ability for NULL colors (delete the hex value). Color will be returned as color.hex == ''. Can set the default color to an empty hex string as well.
  - cancelCallback now returns the original color for use in programming responses.

- ### V1.0.10:

  - Corrected table layout and tweaked display for more consisent presentation. Nice catch from Jonathan Pasquier.

- ### V1.0.9:

  - Added optional title variable for each jPicker window.

- ### V1.0.8:

  - Moved all images into a few sprites - now using backgroundPosition to change color maps and bars instead of changing the image - this should be faster to download and run.

- ### V1.0.7:

  - RENAMED CSS FILE TO INCLUDE VERSION NUMBER!!! YOU MUST USE THIS VERSIONED CSS FILE!!! There will be no need to do your own CSS version number increments from now on.
  - Added opacity feedback to color preview boxes.
  - Removed reliance on "id" value of containing object. Subobjects are now found by class and container instead of id's. This drastically reduces injected code.
  - Removed (jQuery).jPicker.getListElementById(id) function since "id" is no longer incorporated or required.

- ### V1.0.6:

  - Corrected picker bugs introduced with 1.0.5.
  - Removed alpha slider bar until activated - default behavior for alpha is now OFF.
  - Corrected Color constructor bug not allowing values of 0 for initial value (it was evaluating false and missing the init code - Thanks Pavol).
  - Removed title tags (tooltips) from color maps and bars - They get in the way in some browsers (e.g. IE - dragging marker does NOT prevent or hide the tooltip).
  - THERE WERE CSS FILE CHANGES WITH THIS UPDATE!!! IF YOU USE NEVER-EXPIRE HEADERS, YOU WILL NEED TO INCREMENT YOUR CSS FILE VERSION NUMBER!!!

- ### V1.0.5:

  - Added opacity support to picker and color/callback methods. New property "a" (alpha - range from 0-100) in all color objects now - defaults to 100% opaque. (Thank you Pavol)
  - Added title attributes to input elements - gives short tooltip directions on what button or field does.
  - Commit callback used to fire on control initialization (twice actually) - This has been corrected, it does not fire on initialization.
  - THERE WERE CSS FILE CHANGES WITH THIS UPDATE!!! IF YOU USE NEVER-EXPIRE HEADERS, YOU WILL NEED TO INCREMENT YOUR CSS FILE VERSION NUMBER!!!

- ### V1.0.4:

  - Added ability for smaller picker icon with expandable window on any DOM element (not just input).
  - "draggable" property renamed to "expandable" and its scope increased to create small picker icon or large static picker.

- ### V1.0.3

  - Added cancelCallback function for registering an external function when user clicks cancel button. (Thank you Jeff and Pavol)

- ### V1.0.2

  - Random bug fixes - speed concerns.

- ### V1.0.1

  - Corrected closure based memeory leak - there may be others?

- ### V1.0.0

  - First Release.