Configurator
Type
Palette
Picker
<input id="color-picker" value='#276cb8' />
$('#color-picker').spectrum();
Usage
CDN
<script src="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.js"><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.css">
npm
npm install spectrum-colorpicker2
Download files
<script src="spectrum.min.js"><link rel="stylesheet" type="text/css" href="spectrum.min.css">
All Options
$("#picker").spectrum({ color: tinycolor, type: sting, // text, component, color, flat showInput: bool, showInitial: bool, allowEmpty: bool, showAlpha: bool, disabled: bool, localStorageKey: string, showPalette: bool, showPaletteOnly: bool, togglePaletteOnly: bool, showSelectionPalette: bool, clickoutFiresChange: bool, containerClassName: string, replacerClassName: string, preferredFormat: string, maxSelectionSize: int, palette: [[string]], selectionPalette: [string], // specify locale locale: string, // or directly change the translations cancelText: string, chooseText: string, togglePaletteMoreText: string, togglePaletteLessText: string, clearText: string, noColorSelectedText: string,});
Tip: options can be specified in an options object in the spectrum
initializer, like $(element).spectrum({showAlpha: true })
or on the element's markup, like <input data-show-alpha="true" />
.
Color
The initial color will be set with the color
option. If you don't pass in a color, Spectrum will use the value
attribute on the input.
The color parsing is based on the TinyColor plugin. This should parse any color string you throw at it.
<input type='text' class='basic' value='red' /><input type='text' class='basic' value='#0f0' /><input type='text' class='basic' value='blue' /><br /><input type='text' class='override' /><br /><input type='text' class='startEmpty' value='' />
<script>$(".basic").spectrum();$(".override").spectrum({ color: "yellow"});(".startEmpty").spectrum({ allowEmpty: true});</script>
Show Input
You can add an input to allow free form typing. The color parsing is very permissive in the allowed strings. See TinyColor for more details.
$("#showInput").spectrum({ showInput: true});$("#showInputWithClear").spectrum({ showInput: true, allowEmpty:true});
Show Alpha
You can allow alpha transparency selection. Check out these examples:
$("#showAlpha").spectrum({ showAlpha: true});
Disabled
Spectrum can be automatically disabled if you pass in the disabled
flag. Additionally, if the input that you initialize spectrum on is disabled, this will be the default value. Note: you cannot enable spectrum if the input is disabled (see below).
$("#disabled").spectrum({ disabled: true});$("input:disabled").spectrum({});
Show Palette
Spectrum can show a palette below the colorpicker to make it convenient for users to choose from frequently or recently used colors. When the colorpicker is closed, the current color will be added to the palette if it isn't there already. Check it out here:
$("#showPalette").spectrum({ showPalette: true, palette: [ ['black', 'white', 'blanchedalmond'], ['rgb(255, 128, 0);', 'hsv 100 70 50', 'lightyellow'] ]});
Show Palette Only
If you'd like, spectrum can show the palettes you specify, and nothing else.
$("#showPaletteOnly").spectrum({ showPaletteOnly: true, showPalette:true, color: 'blanchedalmond', palette: [ ['black', 'white', 'blanchedalmond', 'rgb(255, 128, 0);', 'hsv 100 70 50'], ['red', 'yellow', 'green', 'blue', 'violet'] ]});
Toggle Palette Only
Spectrum can show a button to toggle the colorpicker next to the palette. This way, the user can choose from a limited number of colors in the palette, but still be able to pick a color that's not in the palette.
The default value for togglePaletteOnly
is FALSE. Set it to TRUE to enable the Toggle button.
You can also change the text on the Toggle Button with the options togglePaletteMoreText
(default is "more") and togglePaletteLessText
(default is "less").
$("#togglePaletteOnly").spectrum({ showPaletteOnly: true, togglePaletteOnly: true, togglePaletteMoreText: 'more', togglePaletteLessText: 'less', color: 'blanchedalmond', palette: [ ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"], ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"], ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"], ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"], ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"], ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"], ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"], ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"] ]});
Show Selection Palette
Spectrum can keep track of what has been selected by the user with the showSelectionPalette
option.
If the localStorageKey
option is defined, the selection will be saved in the browser's localStorage object
$("#showSelectionPalette").spectrum({ showPalette: true, showSelectionPalette: true, // true by default palette: [ ]});$("#showSelectionPaletteStorage").spectrum({ showPalette: true, showSelectionPalette: true, palette: [ ], localStorageKey: "spectrum.homepage", // Any Spectrum with the same string will share selection});
This colorpicker will store what you pick:
Try switching between the two colorpickers or reloading your page, the chosen colors are always available:
Selection Palette
The default values inside of the selection palette. Make sure that showSelectionPalette and showPalette are both enabled.
If a localStorageKey
is defined, then this value will be overwritten by it.
$("#selectionPalette").spectrum({ showPalette: true, palette: [ ], showSelectionPalette: true, // true by default selectionPalette: ["red", "green", "blue"]});
This colorpicker has default values in the selection palette:
Max Selection Size
This is how many elements are allowed in the selectionPallete at once.
Elements will be removed from the palette in first in - first out order if this limit is reached.
$("#maxSelectionSize").spectrum({ showPalette: true, palette: [ ], showSelectionPalette: true, // true by default selectionPalette: ["red", "green", "blue"], maxSelectionSize: 2});
This colorpicker starts removing selection palette colors older than 2:
Hide After Palette Select
You can have the colorpicker automatically hide after a palette color is selected.
$("#hideAfterPaletteSelect").spectrum({ showPaletteOnly: true, showPalette:true, hideAfterPaletteSelect:true, color: 'blanchedalmond', palette: [ ['black', 'white', 'blanchedalmond', 'rgb(255, 128, 0);', 'hsv 100 70 50'], ['red', 'yellow', 'green', 'blue', 'violet'] ]});
Clickout Fires Change
When clicking outside of the colorpicker, you can force it to fire a change
event rather than having it revert the change. This is true
by default.
$("#clickoutFiresChange").spectrum({ clickoutFiresChange: true});$("#clickoutDoesntChange").spectrum({ clickoutFiresChange: false});
Show Initial
Spectrum can show the color that was initially set when opening. This provides an easy way to click back to what was set when opened.
$("#showInitial").spectrum({ showInitial: true});
Show Input and Initial
If you specify both the showInput
and showInitial
options, the CSS keeps things in order by wrapping the buttons to the bottom row, and shrinking the input. Note: this is all customizable via CSS.
$("#showInputAndInitial").spectrum({ showInitial: true, showInput: true});
Show Input, Initial, and Clear
If you specify both the showInput
, showInitial
, and allowEmpty
options, the CSS keeps things in order by wrapping the buttons to the bottom row, and shrinking the input. Note: this is all customizable via CSS.
$("#showInputInitialClear").spectrum({ allowEmpty:true, showInitial: true, showInput: true});
Internationalisation
Specify `locale` so choose a language. If not specified, spectrum will try to use the navigator language. Alternatly, you can directly specify translated text with cancelText
, chooseText
, togglePaletteMoreText
, togglePaletteLessText
, clearText
and noColorSelectedText
properties.
$("#buttonText").spectrum({ locale: "fr" chooseText: "OK!" // use 'OK' instead of 'Valider'});
Show Buttons
You can show or hide the buttons using the showButtons
property. If there are no buttons, the behavior will be to fire the `change` event (and update the original input) when the picker is closed.
$("#hideButtons").spectrum({ showButtons: false});
Container Class Name
You can add an additional class name to the just the container element using the containerClassName
property.
$("#containerClassName").spectrum({ containerClassName: 'awesome'});
.awesome { background: purple;}
Replacer Class Name
You can add an additional class name to just the replacer element using the replacerClassName
property.
$("#replacerClassName").spectrum({ replacerClassName: 'awesome'});
.awesome { background: purple;}
Preferred Format
You can set the format that is displayed in the text box.
This will also change the format that is displayed in the titles from the palette swatches.
$("#preferredHex").spectrum({ preferredFormat: "hex", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]]});$("#preferredHex3").spectrum({ preferredFormat: "hex3", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]]});$("#preferredHsl").spectrum({ preferredFormat: "hsl", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]]});$("#preferredRgb").spectrum({ preferredFormat: "rgb", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]]});$("#preferredName").spectrum({ preferredFormat: "name", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]]});$("#preferredNone").spectrum({ showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]]});
Hex
Hex (3 Characters If Possible)
Hsl
Rgb
Name (Falls back to hex)
None (Depends on input - try changing formats with the text box)
appendTo
You can choose which element the colorpicker container is appended to (default is "body"
). This can be any valid object taken into the jQuery appendTo function.
Changing this can help resolve issues with opening the colorpicker in a modal dialog or fixed position container, for instance.
Events
// Events can be bound in the intialization process as options:$("#picker").spectrum({ move: function(tinycolor) { }, show: function(tinycolor) { }, hide: function(tinycolor) { }, beforeShow: function(tinycolor) { },});// Alternatively, they can be added as an event listener:$("#picker").on('move.spectrum', function(e, tinycolor) { });$("#picker").on('show.spectrum', function(e, tinycolor) { });$("#picker").on('hide.spectrum', function(e, tinycolor) { });$("#picker").on('beforeShow.spectrum', function(e, tinycolor) { });
change
Called as the original input changes. Only happens when the input is closed or the 'Choose' button is clicked.
change: function(color) { color.toHexString(); // #ff0000}
move
Called as the user moves around within the colorpicker
move: function(color) { color.toHexString(); // #ff0000}
hide
Called after the colorpicker is hidden. This happens when clicking outside of the picker while it is open. Note, when any colorpicker on the page is shown it will hide any that are already open. This event is ignored on a flat colorpicker.
hide: function(color) { color.toHexString(); // #ff0000}
show
Called after the colorpicker is opened. This is ignored on a flat colorpicker. Note, when any colorpicker on the page is shown it will hide any that are already open.
show: function(color) { color.toHexString(); // #ff0000}
beforeShow
You can prevent the colorpicker from showing up if you return false in the beforeShow event. This event is ignored on a flat colorpicker.
beforeShow: function(color) { return false; // Will never show up}
dragstart
Called at the beginning of a drag event on either hue slider, alpha slider, or main color picker areas
$(element).on("dragstart.spectrum", function(e, color) { color.toHexString(); // #ff0000});
dragstop
Called at the end of a drag event on either hue slider, alpha slider, or main color picker areas
$(element).on("dragstop.spectrum", function(e, color) { color.toHexString(); // #ff0000});
Methods
$("#picker").spectrum("show");$("#picker").spectrum("hide");$("#picker").spectrum("toggle");$("#picker").spectrum("get");$("#picker").spectrum("set", colorString);$("#picker").spectrum("container");$("#picker").spectrum("reflow");$("#picker").spectrum("destroy");$("#picker").spectrum("enable");$("#picker").spectrum("disable");$("#picker").spectrum("option", optionName);$("#picker").spectrum("option", optionName, newOptionValue);
show
Shows the colorpicker.
hide
Hides the colorpicker.
toggle
Toggles the colorpicker.
Warning: If you are calling toggle from a click handler, make sure you return false
to prevent the colorpicker from immediately hiding after it is toggled.
$("#btn-toggle").click(function() { $("#toggle").spectrum("toggle"); return false;});
get
Gets the current value from the colorpicker.
set
Setting the colorpicker programmatically will update the original input.
Note: this will not fire the change
event, to prevent infinite loops from calling set
from within change
.
<input type='text' value='blanchedalmond' name='triggerSet' id='triggerSet' /><input type='text' placeholder='Enter A Color' id='enterAColor' /><button id='btnEnterAColor'>Trigger Set</button><script>$("#triggerSet").spectrum();// Show the original input to demonstrate the value changing when calling `set`$("#triggerSet").show();$("#btnEnterAColor").click(function() { $("#triggerSet").spectrum("set", $("#enterAColor").val());});</script>
container
Retrieves the container element of the colorpicker, in case you want to manaully position it or do other things.
reflow
Resets the positioning of the container element. This could be used was hidden when initialized, or if the colorpicker is inside of a moving area.
destroy
Removes the colorpicker functionality and restores the element to its original state.
enable
Allows selection of the colorpicker component. If it is already enabled, this method does nothing.
Additionally, this will cause the original (now hidden) input to be set as disabled.
disable
Disables selection of the colorpicker component. Adds the sp-disabled
class onto the replacer element. If it is already disabled, this method does nothing.
Additionally, this will remove the disabled
property on the original (now hidden).
option
Calling option
with an option name will return the current value of that option. So, for example:
$("input").spectrum({ showInput: true});$("input").spectrum("option", "showInput"); // true
Calling option
with an option name and an option value will set the option to the new value.
$("input").spectrum({ showInput: true});$("input").spectrum("option", "showInput", false);$("input").spectrum("option", "showInput"); // false
Other
Non-input elements
You can use any element you would like to trigger the colorpicker: Click me to open a colorpicker, though it is strongly recommended to stick with <input>
tags.
input[type=color]
If you just want to provide a polyfill for the native color input, the easiest way is to create an input with the type of color. Once a user's browser supports a native color control, it will opt to use their native control instead.
Unlike the other modes, your value must be a 6 character hex value starting with a '#'. Why? Because the spec says so, that's why.
<input type='color' name='color' /><input type='color' name='color2' value='#3355cc' />
That's it! The field will degrade to a text input if the user does not have JavaScript enabled, so that they will still be able to manually enter a color. You don't need to add a single line of code.
Browser Support
I wanted this to work in the latest and greatest browsers, but also target backwords compatibility and mobile support. Here are the currently supported browers:
- IE 6+
- Chrome 4+
- Firefox 3.6+
- Safari 4+
- Opera 11.1+
- iOS
IE Implementation
IE Support is provided using proprietary filters. Other browsers use CSS gradients.
Accepted Color Inputs
Spectrum will use the color passed in to initialize. If there is no color passed in, it will try to parse a color based on the value
of the input. The color parsing is based on the TinyColor plugin, and accepts many forms of input:
red#ffffff#ffffffffffffrgb(255, 0, 0)rgb 255 0 0hsl(0, 100, 50)hsl(0, 100%, 50%)hsl 0 100 50hsl 0 100% 50%hsv(0, 100%, 100%)hsv(0, 100, 100)hsv 0 100% 100%hsv 0 100 100
It also provides the following forms of output:
var t = $("#element").spectrum("get");t.toHex() // "ff0000"t.toHexString() // "#ff0000"t.toRgb() // {"r":255,"g":0,"b":0}t.toRgbString() // "rgb(255, 0, 0)"t.toHsv() // {"h":0,"s":1,"v":1}t.toHsvString() // "hsv(0, 100%, 100%)"t.toHsl() // {"h":0,"s":1,"l":0.5}t.toHslString() // "hsl(0, 100%, 50%)"t.toName() // "red"
Share
If you've made it this far, please share one of these links to help others find this project!
JavaScript Colorpicker | jQuery Colorpicker | Mobile Colorpicker | Spectrum colorpicker
Thanks to all the spectrum contributors for committing code, documentation, and translations.