'Hello world' example

<script src="jscolor.js"></script>

Your favorite color: <input value="ab2567" data-jscolor="">

Installation

Step 1: Get jscolor.js

Get jscolor.js using one of the following:

Step 2: Include jscolor.js in your HTML

<script src="jscolor.js"></script>

Step 3: Add data-jscolor attribute

Add data-jscolor attribute to all desired elements (like <input>, <button> or even <span>)

Select color: <input data-jscolor="">

Configuration

Tip: You can use the online Configurator tool to try out most of the configuration options.

To change defaults for all color pickers, just add custom configuration options into the default preset:

jscolor.presets.default = {<default_options>}

Each color picker can also be configured individually by putting its configuration in data-jscolor attribute. Such options will override any inherited configuration.

For example:

Note on security: The data-jscolor attribute shouldn't be allowed to be set by an untrusted party.

Presets

In jscolor, a preset is a set of predefined configuration options which can be applied by simply specifying preset name(s) when creating a color picker. There are some built-in presets which can be used straight away, but you can also create your own.

Built-in presets

  • Default preset:
    • default - an empty preset that can be customized. All color pickers use it as a baseline configuration.
  • Color theme presets:
    • light (default colors)
    • dark
  • Picker size presets:
    • small
    • medium (default size)
    • large
  • Other presets:
    • thin - thin borders and controls (default thickness)
    • thick - thick borders and controls

Using presets

To apply a configuration preset to a color picker, just name the preset in the preset configuration option.

You can combine multiple presets together by providing a space-separated list. Should there be any overlapping options, then the former preset overrides the latter.

<input data-jscolor="{preset:'<preset1> <preset2> …'}">
For example, this will create a large dark color picker on <input> element:
<input data-jscolor="{preset:'dark large'}">

Creating custom presets

You can create and use a custom preset this way:

Scripting

Accessing color picker instance

Elements with data-jscolor attribute will have their picker instance installed in their property <targetElement>.jscolor after DOM is loaded. To access this property before that, you can either install the pickers immediately by calling jscolor.install() like in the example below, or instantiate them programmatically.

For example, let's create a color input using this HTML:

<input id="colorInput1" data-jscolor="">

You can access its color picker after DOM is loaded via .jscolor property. This is how to set a custom color:

document.querySelector('#colorInput1').jscolor.fromString('#80FFAA'); // setting a custom color

To call a show() method on it, even before DOM is fully loaded:

jscolor.install(); // to immediately install pickers on elements that have data-jscolor attribute

document.querySelector('#colorInput1').jscolor.show();

Accessing color picker via jQuery

Once DOM is ready, or after calling jscolor.install(), you can access color pickers using jQuery this way:

$('#colorInput1')[0].jscolor.fromString('#80FFAA'); // setting a custom color

Creating new picker instance

In addition to installing using HTML attribute data-jscolor, you can also create new color pickers programmatically using new keyword:

var myPicker = new JSColor(<targetElement>, <options>)

Note: JSColor is an alias to lowercase jscolor

  • <targetElement> (node or CSS selector) – The DOM node that will display a color picker upon mouse click. The value is either a DOM node or CSS selector, e.g. '#colorInput1'

  • <options> (object) – an optional hashmap with configuration options and their values in format {<option>:<value>, …}
    You can also specify one or more presets using a preset option, e.g. preset:'dark large'

To call a show() method on myPicker:

myPicker.show()

Configuring a picker instance

It is recommended that the picker options are set as a parameter when creating a picker instance, if they are already known at that point.

Most options can also be changed afterwards using the option() method. For example:

API Reference

Configuration options

  • alpha (string)

    Initial color's alpha value (opacity).

    Note: To change the alpha value later in the script, call channel('A', <value>). To read it, call channel('A')

    Note: When alpha option is set, color picker will automatically display the alpha slider.

  • alphaChannel (mixed)  = 'auto'

    Specifies whether the alpha channel is enabled and the alpha slider is visible.

    • 'auto' - automatically enable alpha channel if the current format supports it or if an alpha-related option is set (alpha, alphaElement)
    • true - enable the alpha channel (alpha slider will be visible)
    • false - disable the alpha channel (color will maintain 100% opacity)
  • alphaElement (node or CSS selector)

    DOM element that will be used to edit/display the alpha value (opacity).

    This is particularly useful when you wish to work with alpha channel, but keep the color value in a HEX or RGB format, which doesn't specify opacity.

    Usually, it is a text <input>, so that the user can edit the alpha value. To include the chosen alpha in submitted <form> data, but make it hidden to the user, use <input type="hidden">

    You can also use any other element, such as <span>, in which case the alpha value will be displayed as its read-only text content.

    Note: When alphaElement is set, color picker will automatically display the alpha slider.

  • backgroundColor (string)  = 'rgba(255,255,255,1)'

    Color picker's background color (in CSS color notation)

  • borderColor (string)  = 'rgba(187,187,187,1)'

    Border color of the color picker box (in CSS color notation)

  • borderRadius (number)  = 8

    Border radius (px) of the color picker box

  • borderWidth (number)  = 1

    Border width (px) of the color picker box

  • buttonColor (string)  = 'rgba(0,0,0,1)'

    Foreground color of the Close button, i.e. its border and text color (in CSS color notation)

  • buttonHeight (number)  = 18

    Height (px) of the Close button

  • closeButton (boolean)  = false

    Whether to display a Close button

  • closeText (string)  = 'Close'

    Text of the Close button

  • container (node)  = document.body

    (Experimental option) Specifies where to append the color picker's box (BODY element by default)

  • controlBorderColor (string)  = 'rgba(187,187,187,1)'

    Border color of the color picker's controls (in CSS color notation)

  • controlBorderWidth (number)  = 1

    Border width (px) of the color picker's controls

  • crossSize (number)  = 8

    Size (px) of the cross-shaped pointer

  • forceStyle (boolean)  = true

    Whether to overwrite CSS style of the previewElement using !important flag

  • format (string)  = 'auto'

    Specifies a format to be used for displaying color value.

    • 'auto' - automatically detect format from the initial color value and keep it in effect
    • 'any' - user can enter a color code in any supported format (and it will stay in that format until different one is used)
    • 'hex' - HEX color in CSS notation #RRGGBB
    • 'hexa' - HEX color in CSS notation #RRGGBBAA
    • 'rgb' - RGB color in CSS notation rgb(r,g,b)
    • 'rgba' - RGBA color in CSS notation rgba(r,g,b,a)

    Note: When entering a color code in a different format than is currently in effect, the color will be converted. However, if format is set to 'any', the format will keep adapting to user-entered value. This way, it is always possible to e.g. paste a HEX color into RGBA color input.

  • hash (boolean)  = true

    Whether the valueElement should have its HEX color code prefixed with '#'. Only applicable to HEX color format.

  • height (number)  = 101

    Height (px) of the color spectrum area

  • hideOnLeave (boolean)  = true

    Whether to automatically hide the picker when user leaves its target element (e.g. upon clicking the document)

  • hideOnPaletteClick (boolean)  = false

    When set to true, clicking the palette will also hide the color picker.

  • mode (string)  = 'HSV'

    Layout of the color picker controls.

    • 'HSV' - hue and saturation are displayed as 2D gradient, value (brightness) is in the slider
    • 'HVS' - hue and value (brightness) are displayed as 2D gradient, saturation is in the slider
    • 'HS' - hue and saturation are displayed as 2D gradient, no slider (experimental setting)
    • 'HV' - hue and value (brightness) are displayed as 2D gradient, no slider (experimental setting)
  • onChange (function | string)

    A callback function that is called when the color changes, e.g. after releasing a mouse button or leaving an input field.

    The value can be either a function or a string with JavaScript code.

    The this variable in the callback function refers to the current color picker instance, so you can use, for example, this.toRGBAString() to get the current color in a CSS-compatible rgba format.

  • onInput (function | string)

    A callback function that is called repeatedly as the color is being changed, e.g. while dragging a slider or typing a color code.

    The value can be either a function or a string with JavaScript code.

    The this variable in the callback function refers to the current color picker instance, so you can use, for example, this.toRGBAString() to get the current color in a CSS-compatible rgba format.

  • padding (number)  = 12

    Padding (px) of the color picker box

  • palette (array | string)  = []

    Colors to be displayed in the palette (swatch), specified as an array or a string of space separated color values (in any supported format).

    Both of the following palette values are valid:

    • String notation:

      '#ffe438 #88dd20 rgba(0,154,255,0.6) rgba(187,0,255,0.3)'
    • Array notation:

      ['#ffe438', '#88dd20', 'rgba(0,154,255,0.6)', 'rgba(187,0,255,0.3)']
  • paletteCols (number)  = 10

    Number of columns in the palette.

  • paletteHeight (number)  = 16

    Maximum height (px) of a row in the palette.

  • paletteSetsAlpha (mixed)  = 'auto'

    • 'auto' - palette colors that don't specify alpha will set alpha to 1.0, but only if the palette contains at least one color with transparency (alpha < 1.0)
    • true - palette colors that don't specify alpha will set alpha to 1.0
    • false - palette colors that don't specify alpha will not change alpha

    Note: "Palette colors that don't specify alpha" are colors in hex or rgb format.

  • paletteSpacing (number)  = 4

    Distance (px) between color samples in the palette.

  • pointerBorderColor (string)  = 'rgba(255,255,255,1)'

    Border color of the pointers inside the color picker's controls (in CSS color notation)

  • pointerBorderWidth (number)  = 1

    Border width (px) of the pointers inside the color picker's controls

  • pointerColor (string)  = 'rgba(76,76,76,1)'

    Color of the pointers inside the color picker's controls (in CSS color notation)

  • pointerThickness (number)  = 2

    Thickness (px) of the pointers inside the color picker's controls

  • position (string)  = 'bottom'

    Position of the color picker relative to the target element.

    Possible values:

    • 'left'
    • 'right'
    • 'top'
    • 'bottom'

    Note: If there is not enough space for the picker at the chosen position, a more suitable position will be used according to available space on page (unless smartPosition is disabled).

  • previewElement (node or CSS selector)  = targetElement

    DOM element that will contain a preview of the picked color using CSS background image. For example, you can use a custom div element to display the selected color in it.

    If not specified, the original target element will be used (the one that shows jscolor upon clicking it).

  • previewPadding (number)  = 8

    A space (px) between the color preview image and content of the previewElement, in case the preview image is aligned to a side.

    Note: Only text inputs and non-empty buttons have their preview image aligned to a side, other elements will have it tiled over their entire surface.

  • previewPosition (string)  = 'left'

    Position of the color preview image in the previewElement.

    Possible values: 'left', 'right'

    Note: Only text inputs and non-empty buttons have their preview image aligned to a side, other elements will have it tiled over their entire surface.

  • previewSize (number)  = 32

    Width (px) of the color preview image in the previewElement, in case it is aligned to a side.

    Note: Only text inputs and non-empty buttons have their preview image aligned to a side, other elements will have it tiled over their entire surface.

  • random (boolean | array)  = false

    Setting this property to true (or an array) will generate a random initial color for the picker by calling randomize() method on it.

    Value true generates a random color within full range of possible V, S, H values.

    If you wish to restrict some of the channels to a specific range, you can specify minimum and maximum boundaries for channels V, S, H, A (value, saturation, hue, alpha) as an array.

    The following value will generate a random color within range: Value = 80–100, Saturation = 10–20, Hue = 0–359

    [80, 100, 10, 20, 0, 359]

    See also fromHSVA() method for a list of minimum and maximum values for each channel.

  • required (boolean)  = true

    Whether the valueElement must always contain some color value. If set to false, it can be left empty.

  • shadow (boolean)  = true

    Whether to display a shadow behind the color picker

  • shadowBlur (number)  = 15

    Blur radius (px) of the color picker's shadow

  • shadowColor (string)  = 'rgba(0,0,0,0.2)'

    Color of the color picker's shadow (in CSS color notation)

  • showOnClick (boolean)  = true

    Whether to display the color picker when user clicks on its target element

  • sliderSize (number)  = 16

    Width (px) of a slider

  • smartPosition (boolean)  = true

    When enabled, picker will automatically choose a more suitable position if there is not enough space for it at the specified position.

  • uppercase (boolean)  = true

    Whether the valueElement should have its HEX color code in uppercase. Only applicable to HEX color format.

  • value (string)

    Initial color value in any supported format. If not set, jscolor will attempt to take the color from the value attribute of the valueElement (since valueElement is usually a text <input>).

    Note: To change the color value later in the script, use method fromString(), fromHSVA(), fromRGBA() or channel()

    Note: To read the color value, use method toString(), toHEXAString(), toHEXString(), toRGBAString(), toRGBString() or channel()

  • valueElement (node or CSS selector)

    DOM element that will be used to edit/display the color code.

    Usually, it is the target <input> itself (the one with data-jscolor attribute).

    You can specify custom element to be used as valueElement. In order to let users edit the color code, it should be a text <input>. To include the chosen color in submitted <form> data, but make it hidden to the user, use <input type="hidden">

    You can also use any other element, such as <span>, in which case the color code will be displayed as its read-only text content.

    Events: The onChange and onInput event will be triggered on valueElement when user changes the color (with onInput being called more often)

    Default value: depends on the type of picker's target element:

    • for text <input> targets, default valueElement is the target <input> itself
    • for other target elements, such as buttons, default valueElement is not set
  • width (number)  = 181

    Width (px) of the color spectrum area

  • zIndex (number)  = 5000

    z-index of the color picker box

Static properties

  • jscolor.activeClassName (string)  = 'jscolor-active'

    Class name to be set to the target element when a picker window is open on it

  • jscolor.className (string)  = 'jscolor'

    Class name to be set to the target element when a color picker is created on it

  • jscolor.looseJSON (boolean)  = true

    Specifies whether the configuration in data-jscolor attribute can be in loose JSON format (e.g. with unquoted option names). If set to false, only strict JSON notation can be used.

    • If jscolor.looseJSON = true, the configuration string will be evaluated using new Function() – in case it could not first be parsed with JSON.parse().
    • If jscolor.looseJSON = false, only JSON.parse() will be used.

    Configuration example with jscolor.looseJSON = true (default)

    <input data-jscolor="{position:'right', previewSize:50}">

    JSON notation will work irrespective of jscolor.looseJSON value:

    <input data-jscolor='{"position":"right", "previewSize":50}'>

    Note on security: The data-jscolor attribute shouldn't be allowed to be set by an untrusted party (even if looseJSON is disabled), because it can still contain on<Event> options that execute JavaScript code, similarly to HTML attributes like onchange or oninput.

  • jscolor.presets (object)  = {...}

    A hashmap of presets and their configuration options. See the Presets section for more information.

Static methods

  • jscolor.hide()

    Hides current color picker box.

  • jscolor.init()

    Initializes jscolor by connecting necessary event handlers to document and calling the install() method.

    Note: This method is called automatically when DOM is loaded, there is no need to call it on DOMContentLoaded event.

  • jscolor.install(rootNode) (return: boolean)

    • optional rootNode (node or CSS selector) - where to search for elements using query selector. Defaults to document node.

    Installs jscolor on elements having data-jscolor attribute. Call this method if you wish to already access color pickers on current DOM, or in case of dynamically generated HTML content (e.g. using AJAX) to install jscolor on newly created elements.

    Note: This method is called automatically when DOM is loaded, there is no need to call it on DOMContentLoaded event.

  • jscolor.ready(func)

    Registers function to be called as soon as jscolor is initialized (or immediately, if it already is). This means the function will be called when all color pickers on the page are ready.

  • jscolor.trigger(eventNames)

    • eventNames (string) - one or more space-separated event names, e.g. 'change input'

    Triggers given event on all color pickers. If called before jscolor is initialized, then the events will be postponed until initialization is done.

    The method triggers both following types of events:

    1. standard HTML event handler specified by HTML attribute onEvent="<script>" on the <input> element (valueElement)
    2. onEvent handler specified as picker's configuration option

    For example, the following code will trigger onInput and onChange event on all color pickers as soon as jscolor is initialized (or immediately, if it already is).

    jscolor.trigger('input change')

Picker instance methods

  • <pickerInstance>.channel(...) (return: mixed)

    Sets or gets value of a color channel.

    • channel(name) - returns value of the specified color channel
    • channel(name, value) - sets value of the specified color channel, returns true if successful

    Available color channels and their value ranges:

    • R - red (0–255)
    • G - green (0–255)
    • B - blue (0–255)
    • H - hue (0–360)
    • S - saturation (0–100)
    • V - value (brightness) (0–100)
    • A - alpha (opacity) (0.0–1.0)
  • <pickerInstance>.fromHSVA(h, s, v, a) (return: boolean)

    • h (number) - Hue in range 0–360
    • s (number) - Saturation in range 0–100
    • v (number) - Value in range 0–100
    • a (number) - Alpha in range 0.0–1.0

    Sets current picked color by specifying hue, saturation and value (brightness) channel. Returns true if successful.

    Use null instead of a numerical value to keep a channel unchanged.

  • <pickerInstance>.fromRGBA(r, g, b, a) (return: boolean)

    • r (number) - Red in range 0–255
    • g (number) - Green in range 0–255
    • b (number) - Blue in range 0–255
    • a (number) - Alpha in range 0.0–1.0

    Sets current picked color by specifying red, green and blue channel. Returns true if successful.

    Use null instead of a numerical value to keep a channel unchanged.

  • <pickerInstance>.fromString(str) (return: boolean)

    Sets current picked color from a string. The input color format is identical to that of CSS. Returns false if the input string could not be parsed.

    Supported input formats:

    • HEX and HEXA: Standard CSS notation is supported: #RGB, #RRGGBB, or #RRGGBBAA. Letter case is not important and the leading '#' is optional. Examples of valid input: F96, #C09, #a3cc0b, #a3cc0b80

    • RGB and RGBA: Standard CSS notation rgb(r,g,b) and rgba(r,g,b,a) is supported. Letter case is not important. Whitespace around numerical values is optional. Examples of valid input: rgb(80, 0, 255), rgba(255,0,255,0.25)

  • <pickerInstance>.getFormat() (return: string)

    Returns the color format currently in effect.

  • <pickerInstance>.hide()

    Hides the color picker box, if displayed.

  • <pickerInstance>.isLight() (return: boolean)

    Returns true if the grayscale value of the current picked color is closer to white than to black. This is useful for determining color of a text displayed over the picked color – to make the font white when the color is too dark and vice versa, so that it stays readable.

  • <pickerInstance>.option(...) (return: mixed)

    Sets or gets value of a configuration option.

    • option(name) - returns value of the specified option
    • option(name, value) - sets value of the specified option, returns true if successful
    • option({name:value, }) - sets multiple options, returns true if successful
  • <pickerInstance>.randomize(minV=0, maxV=100, minS=0, maxS=100, minH=0, maxH=359, minA=1, maxA=1)

    Generates a random color and sets it to the picker.

    If you wish to restrict some of the channels to a specific range, you can specify minimum and maximum boundaries for channels V, S, H, A (value, saturation, hue, alpha). Note that generated alpha value is always 1.0 (100% opaque), unless you specify minA parameter.

  • <pickerInstance>.show()

    Shows the color picker box.

  • <pickerInstance>.toBackground() (return: string)

    Returns a value for CSS background property containing current color rendered over a gray chessboard pattern (to indicate a level of transparency).

    To preview the currently picked color as a background, you can use:

    element.style.background = picker.toBackground();
  • <pickerInstance>.toGrayscale() (return: number)

    Returns a grayscale value of the current picked color in range between 0–255, taking into account individual luminosity of each of the RGB channels.

  • <pickerInstance>.toHEXAString() (return: string)

    Returns a CSS color code of the current picked color in HEX+alpha format #RRGGBBAA

    Range: #00000000#FFFFFFFF (always in uppercase letters and including leading '#')

  • <pickerInstance>.toHEXString() (return: string)

    Returns a CSS color code of the current picked color in HEX format #RRGGBB

    Range: #000000#FFFFFF (always in uppercase letters and including leading '#')

  • <pickerInstance>.toRGBAString() (return: string)

    Returns a CSS color code of the current picked color in format rgba(r,g,b,a)

    Range: rgba(0,0,0,0)rgba(255,255,255,1). The R, G, B values are rounded to a whole number, the Alpha value is rounded to two decimals.

  • <pickerInstance>.toRGBString() (return: string)

    Returns a CSS color code of the current picked color in format rgb(r,g,b)

    Range: rgb(0,0,0)rgb(255,255,255). All numerical values are rounded to a whole number.

  • <pickerInstance>.toString(format) (return: string)

    Returns a CSS color code of the current picked color.

    If format is set, the color value returned will be in the specified format. Otherwise, the currently used format will be chosen.

    Supported formats: hex, hexa, rgb, rgba.

  • <pickerInstance>.trigger(eventNames)

    • eventNames (string) - one or more space-separated event names, e.g. 'change input'

    Triggers given event on the color picker.

    The method triggers both following types of events:

    1. standard HTML event handler specified by HTML attribute onEvent="<script>" on the <input> element (valueElement)
    2. onEvent handler specified as picker's configuration option