Hello world example

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

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

Installation

Step 1: Download / npm install / CDNJS

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 <input> or <button> elements:

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:

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

<script>
// let's set defaults for all color pickers
jscolor.presets.default = {
    height: 181,              // make the picker box a little bigger
    position: 'right',        // position the picker to the right of the target
    previewPosition: 'right', // display color preview on the right side
    previewSize: 40,          // make color preview bigger
};
</script>

Color 1: <input data-jscolor="{}" value="2CAFFE">
Color 2: <input data-jscolor="{}" value="rgba(44,175,254,0.5)">

Optional color 1: <input data-jscolor="{required:false, format:'hex'}">
Optional color 2: <input data-jscolor="{required:false, format:'rgba'}">

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:

<script>
// let's define custom preset
jscolor.presets.myPreset = {
    format: 'any',
    width: 101,
    backgroundColor: '#333',
};
</script>

Color: <input data-jscolor="{preset:'myPreset'}">

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="">

This input will have its picker accessible after DOM is loaded via: document.querySelector('#colorInput1').jscolor

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

jscolor.install(); // to immediately install pickers on elements with data-jscolor

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

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:

var myPicker = new JSColor('#colorInput1');

// let's set a single option
myPicker.option('position', 'right');

// and let's set multiple options at once
myPicker.option({
  'format': 'any',
  'width': 300,
  'previewSize': 80,
});

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 standard CSS notation #RRGGBB
    • 'rgb' - RGB color in standard CSS notation rgb(r,g,b)
    • 'rgba' - RGBA color in standard 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 palette area

  • hideOnLeave (boolean)  = true

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

  • mode (string)  = 'HSV'

    Layout of the color picker controls.

    • 'HSV' - hue and saturation in the palette area, value (brightness) in the slider
    • 'HVS' - hue and value (brightness) in the palette area, saturation in the slider
    • 'HS' - hue and saturation in the palette area, no slider (experimental setting)
    • 'HV' - hue and value (brightness) in the palette area, 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

  • 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 with data-jscolor attribute).

  • 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.

  • 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()
    To read the color value, use method toString(), 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 palette 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

    Whether the configuration in data-jscolor attribute can be in loose JSON format (e.g. with unquoted option names).

    If enabled, the configuration string will be evaluated using new Function() – in case it could not first be parsed with JSON.parse(). If disabled, only JSON.parse() will be used.

    Configuration example with jscolor.looseJSON = true (default)

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

    Configuration example with jscolor.looseJSON = false

    <input data-jscolor='{"position":"right", "previewSize":50}'>
  • jscolor.presets (object)  = {...}

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

Static methods

  • 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.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: Standard CSS notation #RRGGBB and #RGB is supported. Letter case is not important and the leading '#' is optional. Examples of valid input: F96, #C09, #a3cc0b

    • 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>.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>.toHEXString() (return: string)

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

    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.

    The supported formats are: hex, 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