Spectrum Vanilla
The No Hassle Colorpicker with Vanilla JS
Based on popular Spectrum2 package. This version rewrote with TypeScript and drop IE support.
Configurator
Type
<input id="color-picker" value="#276cb8" />
$('#color-picker').spectrum();
Installation
CDN
Includes
<script src="https://unpkg.com/spectrum-vanilla/dist/spectrum.min.js"></script> <link rel="stylesheet" type="text/css" href="https://unpkg.com/spectrum-vanilla/dist/spectrum.min.css"> <!-- Dark theme --> <link rel="stylesheet" type="text/css" href="https://unpkg.com/spectrum-vanilla/dist/spectrum-dark.min.css">
ES Module
<script type="module"> import Spectrum from 'https://unpkg.com/spectrum-vanilla/dist/spectrum.es.min.js'; </script>
npm
npm install spectrum-vanilla
Import in Webpack / TypeScript
import Spectrum from 'spectrum-vanilla';
Download files
Download Zip<script src="spectrum.min.js"></script> <link rel="stylesheet" type="text/css" href="spectrum.min.css">
Usage
Create Instance
Create a new instance by selector, not cache it, you must store this instance yourself
// If this selector not found, will throw Error. const sp = Spectrum.create('#picker', [options]); // Just call methods on this instance. sp.show(); sp.hide(); // If this selector not found, will return NULL. const sp = Spectrum.createIfExists('#picker', [options]); // Create from element const element = document.querySelector('#picker'); const sp = Spectrum.create(element, [options]); // Create from jQuery instance const element = $('#picker'); const sp = Spectrum.create(element, [options]);
Create multiple new instances
const sps = Spectrum.createMultiple('.picker', [options]); // Array<Spectrum> // Create from elements const elements = document.querySelectorAll('.picker'); const sps = Spectrum.createMultiple(elements, [options]); // Create from jQuery instance const elements = $('.picker'); const sps = Spectrum.createMultiple(elements, [options]);
Singleton
You can get same instance if you use getInstance()
method.
const sp = Spectrum.getInstance('#picker', [options]); // Always same instance sp === Spectrum.getInstance('#picker'); // Get multiple instances const sps = Spectrum.getInstanceMultiple('.picker', [options]);
jQuery
jQuery plugin still available
const sp = $('#picker').spectrum(); $('#picker').spectrum('show'); $('#picker').spectrum('hide');
If you use Spectrum in webpack and jQuery did not auto register, you can register it manually.
import Spectrum from 'spectrum-vanilla'; import jQuery from 'jquery'; Spectrum.registerJQuery(jQuery); const sp = jQuery('#picker').spectrum();
Vue
A simple example that create a Vue3 directive
const SpectrumDirective = { mounted(el, { value }) { Spectrum.getInstance(el, Object.assign({}, value)); }, updated(el, { value }) { const sp = Spectrum.getInstance(el, options); if (JSON.stringify(value) !== JSON.stringify(sp.options)) { sp.rebuild(Object.assign({}, value)); } }, unmounted(el) { const sp = Spectrum.getInstance(el); sp.destroy(); } }; app.directive('colorpicker', SpectrumDirective); app.mount('...');
<input type="text" v-colorpciker="{ type: 'component' }">
All Options
Spectrum.getInstance('#picker', { color: tinycolor, type: sting, // text, component, color, flat, Default is "component" 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|object, // or directly change the translations cancelText: string, chooseText: string, togglePaletteMoreText: string, togglePaletteLessText: string, clearText: string, noColorSelectedText: string, });
spectrum
initializer, like Spectrum.getInstance(element, {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> Spectrum.getInstanceMultiple('.basic'); Spectrum.getInstance('.override', { color: "yellow" }); Spectrum.getInstance('.startEmpty', { 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.
Spectrum.getInstance('#showInput', { showInput: true }); Spectrum.getInstance('#showInputWithClear', { showInput: true, allowEmpty:true });
Show Alpha
You can allow alpha transparency selection. Check out these examples:
Spectrum.getInstance('#showAlpha', { 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).
Spectrum.getInstance('#disabled', { 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:
Spectrum.getInstance('#showPalette', { 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.
Spectrum.getInstance('#showPaletteOnly', { 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").
Spectrum.getInstance('#togglePaletteOnly', { 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
Spectrum.getInstance('#showSelectionPalette', { showPalette: true, showSelectionPalette: true, // true by default palette: [ ] }); Spectrum.getInstance('#showSelectionPaletteStorage', { showPalette: true, showSelectionPalette: true, palette: [ ], localStorageKey: "spectrum.homepage", // Any Spectrum with the same string will share selection });
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.
Spectrum.getInstance('#selectionPalette', { showPalette: true, palette: [ ], showSelectionPalette: true, // true by default selectionPalette: ["red", "green", "blue"] });
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.
Spectrum.getInstance('#maxSelectionSize', { showPalette: true, palette: [ ], showSelectionPalette: true, // true by default selectionPalette: ["red", "green", "blue"], maxSelectionSize: 2 });
Hide After Palette Select
You can have the colorpicker automatically hide after a palette color is selected.
Spectrum.getInstance('#hideAfterPaletteSelect', { 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.
Spectrum.getInstance('#clickoutFiresChange', { clickoutFiresChange: true }); Spectrum.getInstance('#clickoutDoesntChange', { 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.
Spectrum.getInstance('#showInitial', { 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.
Spectrum.getInstance('#showInputAndInitial', { 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.
Spectrum.getInstance('#showInputInitialClear', { allowEmpty:true, showInitial: true, showInput: true });
Locale
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.
<script src="dist/spectrum.min.js"> <script src="dist/i18n/fr.js">
Spectrum.getInstance('#buttonText', { locale: "fr" chooseText: "OK!" // Directly override lang text });
To use locale in ES module, you must include from another i18n-es
dir and register it manually.
import Spectrum from './dist/spectrum.es.js'; import zhtw from './dist/i18n-es/zh-tw.js'; Spectrum.locale('zh-tw', zhtw); Spectrum.getInstance('#buttonText', { locale: "zh-tw" });
Or you may just send locale object to options.
import Spectrum from './dist/spectrum.es.js'; import zhtw from './dist/i18n-es/zh-tw.js'; Spectrum.getInstance('#buttonText', { locale: zhtw });
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.
Spectrum.getInstance('#hideButtons', { showButtons: false });
Container Class Name
You can add an additional class name to the just the container element using the containerClassName
property.
Spectrum.getInstance('#containerClassName', { containerClassName: 'awesome' });
.awesome { background: purple; }
Replacer Class Name
You can add an additional class name to just the replacer element using the replacerClassName
property.
Spectrum.getInstance('#replacerClassName', { 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.
Spectrum.getInstance('#preferredHex', { preferredFormat: "hex", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]] }); Spectrum.getInstance('#preferredHex3', { preferredFormat: "hex3", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]] }); Spectrum.getInstance('#preferredHsl', { preferredFormat: "hsl", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]] }); Spectrum.getInstance('#preferredRgb', { preferredFormat: "rgb", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]] }); Spectrum.getInstance('#preferredName', { preferredFormat: "name", showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]] }); Spectrum.getInstance('#preferredNone', { showInput: true, showPalette: true, palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]] });
appendTo
You can choose which element the colorpicker container is appended to (default is "body"
).
This can be any valid DOMElement object or selector string.
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: const sp = Spectrum.getInstance('#picker', { move: function(e) { const color = e.detail.color; }, show: function(e) { }, hide: function(e) { }, beforeShow: function(e) { }, }); // Alternatively, they can be added as an event listener: sp.on('move', function(e) { }); sp.on('show', function(e) { }); sp.on('hide', function(e) { }); sp.on('beforeShow', function(e) { }); // This events will also push to element const ele = document.querySelector('#picker'); ele.addEventListener('change', (e) => { });
change
Called as the original input changes. Only happens when the input is closed or the 'Choose' button is clicked.
change: function(e) { e.detail.color.toHexString(); // #ff0000 }
move
Called as the user moves around within the colorpicker
move: function(e) { e.detail.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(e) { e.detail.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(e) { e.detail.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(e) { 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
sp.on("dragstart", function(e) { e.detail.color.toHexString(); // #ff0000 });
dragstop
Called at the end of a drag event on either hue slider, alpha slider, or main color picker areas
sp.on("dragstop", function(e) { e.detail.color.toHexString(); // #ff0000 });
Methods
sp.show(); sp.hide(); sp.toggle(); sp.get(); sp.set(color); sp.container; sp.reflow(); sp.destroy(); sp.rebuild(); sp.enable(); sp.disable(); sp.option(optionName); sp.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.
toggleButton.addEventListener('click', () => { sp.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> const sp = Spectrum.getInstance('#triggerSet'); // Show the original input to demonstrate the value changing when calling `set` sp.show(); const input = document.querySelector('#enterAColor'); document.querySelector('#btnEnterAColor').addEventListener('click', () => { sp.set(input.value); }); </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:
const sp = Spectrum.getInstance('input', { showInput: true }); sp.option("showInput"); // true
Calling option
with an option name and an option value will set the option to the new value.
const sp = Spectrum.getInstance('input', { showInput: true }); sp.option("showInput", false); sp.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" 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
Spectrum Vanilla use ES2017 syntax and drop the IE support. Here are the currently supported browers:
- Chrome 54+
- Firefox 47+
- Safari 10.1+
- Opera 41+
- iOS 10.3+
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 #fff fff #ffffff ffffff rgb(255, 0, 0) rgb 255 0 0 hsl(0, 100, 50) hsl(0, 100%, 50%) hsl 0 100 50 hsl 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:
const sp = Spectrum.getInstance('#picker'); sp.get().toHex() // "ff0000" sp.get().toHexString() // "#ff0000" sp.get().toRgb() // {"r":255,"g":0,"b":0} sp.get().toRgbString() // "rgb(255, 0, 0)" sp.get().toHsv() // {"h":0,"s":1,"v":1} sp.get().toHsvString() // "hsv(0, 100%, 100%)" sp.get().toHsl() // {"h":0,"s":1,"l":0.5} sp.get().toHslString() // "hsl(0, 100%, 50%)" sp.get().toName() // "red"