Pickr

Flat, simple, multi-themed, responsive and hackable Color-Picker library. N...

README

Logo

    Flat, Simple, Hackable Color-Picker.


gzip size brotli size      alt="Build Status"

src="https://img.shields.io/travis/Simonwep/pickr.svg?style=popout-square">      alt="Download count"
src="https://img.shields.io/npm/dm/@simonwep/pickr.svg?style=popout-square"> No dependencies      alt="JSDelivr download count"
src="https://data.jsdelivr.com/v1/package/npm/@simonwep/pickr/badge">
  <img alt="Current version"
       src="https://img.shields.io/github/tag/Simonwep/pickr.svg?color=3498DB&label=version&style=flat-square">
     alt="Support me" src="https://img.shields.io/badge/github-support-3498DB.svg?style=popout-square">      alt="Gitpod Ready-to-Code"
     src="https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=popout-square"
/>

Fully Featured demo



Get 700+ Material components for the latest Bootstrap 5 for free.

This component is also available as ready-to-use solution in MDB UI Kit. Learn more about Bootstrap Color Picker here.



Features

Themes
Simple usage
Zero dependencies
Multiple color representations
Color comparison
Opacity control
Detail adjustments via. mouse-wheel
Responsive and auto-positioning
Supports touch devices
Swatches for quick-selection
Fully accessible and i18n
Shadow-dom support

Status of this project

This project might continue to get important security- and bug-related updates but its _feature set_ is frozen, and it's highly unlikely that it'll get new features or enhancements.

The reason behind this decision is the way this tool has been build (monolithic, the core is one single file, everything is in plain JS etc.) which makes it incredible hard to maintain, tests become impossible at this stage without a complete rewrite, and the fun is gone at such a level of cramped complexity.

Personally I recommend building these UI-Related "widgets" directly into the app with the framework you're using which takes more time but in return gives you full power of how it should work and look like. Frameworks such as (p)react, vue and svelte will make it a breeze to develop such things within a day.


Update

This project will be archived at the end of 2021!
After this there will be no more bug / security fixes or feature requests.

Themes

|Classic|Monolith|Nano|
|-------|--------|----|
|![Classic

Nano uses css-grid thus it won't work in older browsers.


Getting Started

Node

Note: The readme is always up-to-date with the latest commit. See Releases for installation instructions regarding to the latest version.

Install via npm:
  1. ``` sh
  2. $ npm install @simonwep/pickr
  3. ```

Install via yarn:
  1. ``` sh
  2. $ yarn add @simonwep/pickr
  3. ```

Include code and style:
  1. ``` js

  2. // One of the following themes
  3. import '@simonwep/pickr/dist/themes/classic.min.css';   // 'classic' theme
  4. import '@simonwep/pickr/dist/themes/monolith.min.css';  // 'monolith' theme
  5. import '@simonwep/pickr/dist/themes/nano.min.css';      // 'nano' theme

  6. // Modern or es5 bundle (pay attention to the note below!)
  7. import Pickr from '@simonwep/pickr';
  8. import Pickr from '@simonwep/pickr/dist/pickr.es5.min';
  9. ```

Attention: The es5-bundle (e.g. legacy version) is quite big (around a triple of the modern bundle).

Please take into consideration to use the modern version and add polyfills later to your final bundle!

(Or better: give a hint to users that they should use the latest browsers).

Browsers such as IE are not supported (at least not officially).


Browser


jsdelivr:
  1. ``` html
  2. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/themes/classic.min.css"/> 
  3. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/themes/monolith.min.css"/> 
  4. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/themes/nano.min.css"/> 
  5. <script src="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.min.js"></script>
  6. <script src="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.es5.min.js"></script>
  7. ```

Be sure to load the pickr.min.js (or the es5 version) after pickr.min.css. Moreover the script tag doesn't work with the defer attribute.

Usage

  1. ``` js
  2. // Simple example, see optional options for more configuration.
  3. const pickr = Pickr.create({
  4.     el: '.color-picker',
  5.     theme: 'classic', // or 'monolith', or 'nano'

  6.     swatches: [
  7.         'rgba(244, 67, 54, 1)',
  8.         'rgba(233, 30, 99, 0.95)',
  9.         'rgba(156, 39, 176, 0.9)',
  10.         'rgba(103, 58, 183, 0.85)',
  11.         'rgba(63, 81, 181, 0.8)',
  12.         'rgba(33, 150, 243, 0.75)',
  13.         'rgba(3, 169, 244, 0.7)',
  14.         'rgba(0, 188, 212, 0.7)',
  15.         'rgba(0, 150, 136, 0.75)',
  16.         'rgba(76, 175, 80, 0.8)',
  17.         'rgba(139, 195, 74, 0.85)',
  18.         'rgba(205, 220, 57, 0.9)',
  19.         'rgba(255, 235, 59, 0.95)',
  20.         'rgba(255, 193, 7, 1)'
  21.     ],

  22.     components: {

  23.         // Main components
  24.         preview: true,
  25.         opacity: true,
  26.         hue: true,

  27.         // Input / output Options
  28.         interaction: {
  29.             hex: true,
  30.             rgba: true,
  31.             hsla: true,
  32.             hsva: true,
  33.             cmyk: true,
  34.             input: true,
  35.             clear: true,
  36.             save: true
  37.         }
  38.     }
  39. });
  40. ```

You can find more examples here.


Events

Since version 0.4.x Pickr is event-driven. Use the on(event, cb) and off(event, cb) functions to bind / unbind eventlistener.

EventDescriptionArguments
----------------------------------
`init`Initialization`PickrInstance`
`hide`Pickr`PickrInstance`
`show`Pickr`HSVaColorObject,
`save`User`HSVaColorObject
`clear`User`PickrInstance`
`change`Color`HSVaColorObject,
`changestop`User`eventSource,
`cancel`User`PickrInstance`
`swatchselect`User`HSVaColorObject,

Example:

  1. ``` js
  2. pickr.on('init', instance => {
  3.     console.log('Event: "init"', instance);
  4. }).on('hide', instance => {
  5.     console.log('Event: "hide"', instance);
  6. }).on('show', (color, instance) => {
  7.     console.log('Event: "show"', color, instance);
  8. }).on('save', (color, instance) => {
  9.     console.log('Event: "save"', color, instance);
  10. }).on('clear', instance => {
  11.     console.log('Event: "clear"', instance);
  12. }).on('change', (color, source, instance) => {
  13.     console.log('Event: "change"', color, source, instance);
  14. }).on('changestop', (source, instance) => {
  15.     console.log('Event: "changestop"', source, instance);
  16. }).on('cancel', instance => {
  17.     console.log('Event: "cancel"', instance);
  18. }).on('swatchselect', (color, instance) => {
  19.     console.log('Event: "swatchselect"', color, instance);
  20. });
  21. ```

Where source can be
slider _- Any slider in the UI._
input _- The user input field._
swatch _- One of the swatches._

Options

  1. ``` js
  2. const pickr = new Pickr({

  3.     // Selector or element which will be replaced with the actual color-picker.
  4.     // Can be a HTMLElement.
  5.     el: '.color-picker',

  6.     // Where the pickr-app should be added as child.
  7.     container: 'body',

  8.     // Which theme you want to use. Can be 'classic', 'monolith' or 'nano'
  9.     theme: 'classic',

  10.     // Nested scrolling is currently not supported and as this would be really sophisticated to add this
  11.     // it's easier to set this to true which will hide pickr if the user scrolls the area behind it.
  12.     closeOnScroll: false,

  13.     // Custom class which gets added to the pcr-app. Can be used to apply custom styles.
  14.     appClass: 'custom-class',

  15.     // Don't replace 'el' Element with the pickr-button, instead use 'el' as a button.
  16.     // If true, appendToBody will also be automatically true.
  17.     useAsButton: false,

  18.     // Size of gap between pickr (widget) and the corresponding reference (button) in px
  19.     padding: 8,

  20.     // If true pickr won't be floating, and instead will append after the in el resolved element.
  21.     // It's possible to hide it via .hide() anyway.
  22.     inline: false,

  23.     // If true, pickr will be repositioned automatically on page scroll or window resize.
  24.     // Can be set to false to make custom positioning easier.
  25.     autoReposition: true,

  26.     // Defines the direction in which the knobs of hue and opacity can be moved.
  27.     // 'v' => opacity- and hue-slider can both only moved vertically.
  28.     // 'hv' => opacity-slider can be moved horizontally and hue-slider vertically.
  29.     // Can be used to apply custom layouts
  30.     sliders: 'v',

  31.     // Start state. If true 'disabled' will be added to the button's classlist.
  32.     disabled: false,

  33.     // If true, the user won't be able to adjust any opacity.
  34.     // Opacity will be locked at 1 and the opacity slider will be removed.
  35.     // The HSVaColor object also doesn't contain an alpha, so the toString() methods just
  36.     // print HSV, HSL, RGB, HEX, etc.
  37.     lockOpacity: false,

  38.     // Precision of output string (only effective if components.interaction.input is true)
  39.     outputPrecision: 0,

  40.     // Defines change/save behavior:
  41.     // - to keep current color in place until Save is pressed, set to `true`,
  42.     // - to apply color to button and preview (save) in sync with each change
  43.     //   (from picker or palette), set to `false`.
  44.     comparison: true,

  45.     // Default color. If you're using a named color such as red, white ... set
  46.     // a value for defaultRepresentation too as there is no button for named-colors.
  47.     default: '#42445a',

  48.     // Optional color swatches. When null, swatches are disabled.
  49.     // Types are all those which can be produced by pickr e.g. hex(a), hsv(a), hsl(a), rgb(a), cmyk, and also CSS color names like 'magenta'.
  50.     // Example: swatches: ['#F44336', '#E91E63', '#9C27B0', '#673AB7'],
  51.     swatches: null,

  52.     // Default color representation of the input/output textbox.
  53.     // Valid options are `HEX`, `RGBA`, `HSVA`, `HSLA` and `CMYK`.
  54.     defaultRepresentation: 'HEX',

  55.     // Option to keep the color picker always visible.
  56.     // You can still hide / show it via 'pickr.hide()' and 'pickr.show()'.
  57.     // The save button keeps its functionality, so still fires the onSave event when clicked.
  58.     showAlways: false,

  59.     // Close pickr with a keypress.
  60.     // Default is 'Escape'. Can be the event key or code.
  61.     // (see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
  62.     closeWithKey: 'Escape',

  63.     // Defines the position of the color-picker.
  64.     // Any combinations of top, left, bottom or right with one of these optional modifiers: start, middle, end
  65.     // Examples: top-start / right-end
  66.     // If clipping occurs, the color picker will automatically choose its position.
  67.     // Pickr uses https://github.com/Simonwep/nanopop as positioning-engine.
  68.     position: 'bottom-middle',

  69.     // Enables the ability to change numbers in an input field with the scroll-wheel.
  70.     // To use it set the cursor on a position where a number is and scroll, use ctrl to make steps of five
  71.     adjustableNumbers: true,

  72.     // Show or hide specific components.
  73.     // By default only the palette (and the save button) is visible.
  74.     components: {

  75.         // Defines if the palette itself should be visible.
  76.         // Will be overwritten with true if preview, opacity or hue are true
  77.         palette: true,

  78.         preview: true, // Display comparison between previous state and new color
  79.         opacity: true, // Display opacity slider
  80.         hue: true,     // Display hue slider

  81.         // show or hide components on the bottom interaction bar.
  82.         interaction: {

  83.             // Buttons, if you disable one but use the format in default: or setColor() - set the representation-type too!
  84.             hex: false,  // Display 'input/output format as hex' button  (hexadecimal representation of the rgba value)
  85.             rgba: false, // Display 'input/output format as rgba' button (red green blue and alpha)
  86.             hsla: false, // Display 'input/output format as hsla' button (hue saturation lightness and alpha)
  87.             hsva: false, // Display 'input/output format as hsva' button (hue saturation value and alpha)
  88.             cmyk: false, // Display 'input/output format as cmyk' button (cyan mangenta yellow key )

  89.             input: false, // Display input/output textbox which shows the selected color value.
  90.                          // the format of the input is determined by defaultRepresentation,
  91.                          // and can be changed by the user with the buttons set by hex, rgba, hsla, etc (above).
  92.             cancel: false, // Display Cancel Button, resets the color to the previous state
  93.             clear: false, // Display Clear Button; same as cancel, but keeps the window open
  94.             save: false,  // Display Save Button,
  95.         },
  96.     },

  97.     // Translations, these are the default values.
  98.     i18n: {

  99.         // Strings visible in the UI
  100.        'ui:dialog': 'color picker dialog',
  101.        'btn:toggle': 'toggle color picker dialog',
  102.        'btn:swatch': 'color swatch',
  103.        'btn:last-color': 'use previous color',
  104.        'btn:save': 'Save',
  105.        'btn:cancel': 'Cancel',
  106.        'btn:clear': 'Clear',

  107.        // Strings used for aria-labels
  108.        'aria:btn:save': 'save and close',
  109.        'aria:btn:cancel': 'cancel and close',
  110.        'aria:btn:clear': 'clear and close',
  111.        'aria:input': 'color input field',
  112.        'aria:palette': 'color selection area',
  113.        'aria:hue': 'hue selection slider',
  114.        'aria:opacity': 'selection slider'
  115.     }
  116. });
  117. ```

Selection through a Shadow-DOM

Example setup:
  1. ``` html
  2. <div class="entry">
  3.   #shadow-root
  4.     <div class="innr">
  5.        <div class="another">
  6.          #shadow-root
  7.            <div class="pickr"></div>
  8.        </div>
  9.     </div>
  10. </div>
  11. ```

To select the .pickr element you can use the custom >> shadow-dom-selector in el:
  1. ``` js
  2. el: '.entry >> .innr .another >> .pickr'
  3. ```

Every ShadowRoot of the query-result behind a >> gets used in the next query selection.
An alternative would be to provide the target-element itself as el.

The HSVaColor object

As default color representation is hsva (hue, saturation, value and alpha) used, but you can also convert it to other formats as listed below.

hsva.toHSVA() _- Converts the object to a hsva array._
hsva.toHSLA() _- Converts the object to a hsla array._
hsva.toRGBA() _- Converts the object to a rgba array._
hsva.toHEXA() _- Converts the object to a hexa-decimal array._
hsva.toCMYK() _- Converts the object to a cmyk array._
hsva.clone() _- Clones the color object._

The toString() is overridden, so you can get a color representation string.

  1. ``` js
  2. hsva.toRGBA(); // Returns [r, g, b, a]
  3. hsva.toRGBA().toString(); // Returns rgba(r, g, b, a) with highest precision
  4. hsva.toRGBA().toString(3); // Returns rgba(r, g, b, a), rounded to the third decimal
  5. ```

Methods

pickr.setHSVA(h:Number,s:Number,v:Number,a:Float, silent:Boolean) _- Set an color, returns true if the color has been accepted._
pickr.setColor(str: :String | null, silent:Boolean):Boolean _- Parses a string which represents a color (e.g. #fff, rgb(10, 156, 23)) or name e.g. 'magenta', returns true if the color has been accepted. null will clear the color._

If silent is true (Default is false), the button won't change the current color.

pickr.on(event:String, cb:Function):Pickr _- Appends an event listener to the given corresponding event-name (see section Events)._
pickr.off(event:String, cb:Function):Pickr _- Removes an event listener from the given corresponding event-name (see section Events)._
pickr.show():Pickr _- Shows the color-picker._
pickr.hide():Pickr _- Hides the color-picker._
pickr.disable():Pickr _- Disables pickr and adds the disabled class to the button._
pickr.enable():Pickr _- Enables pickr and removes the disabled class from the button._
pickr.isOpen():Pickr _- Returns true if the color picker is currently open._
pickr.getRoot():Object _- Returns the dom-tree of pickr as tree-structure._
pickr.getColor():HSVaColor _- Returns the current HSVaColor object._
pickr.getSelectedColor():HSVaColor _- Returns the currently applied color._
pickr.destroy() _- Destroys all functionality._
pickr.destroyAndRemove() _- Destroys all functionality and removes the pickr element including the button._
pickr.setColorRepresentation(type:String):Boolean _- Change the current color-representation. Valid options are HEX, RGBA, HSVA, HSLA and CMYK, returns false if type was invalid._
pickr.getColorRepresentation():String _- Returns the currently used color-representation (eg. HEXA, RGBA...)_
pickr.applyColor(silent:Boolean):Pickr _- Same as pressing the save button. If silent is true the onSave event won't be called._
pickr.addSwatch(color:String):Boolean _- Adds a color to the swatch palette. Returns true if the color has been successful added to the palette._
pickr.removeSwatch(index:Number):Boolean_- Removes a color from the swatch palette by its index, returns true if successful._

Static methods

Pickr
create(options:Object):Pickr _- Creates a new instance._

Pickr.utils
once(element:HTMLElement, event:String, fn:Function[, options :Object]) _- Attach an event handle which will be fired only once_
on(elements:HTMLElement(s), events:String(s), fn:Function[, options :Object]) _- Attach an event handler function._
off(elements:HTMLElement(s), event:String(s), fn:Function[, options :Object]) _- Remove an event handler._
createElementFromString(html:String):HTMLElement _- Creates an new HTML Element out of this string._
eventPath(evt:Event):[HTMLElement] _- A polyfill for the event-path event propery._
createFromTemplate(str:String) _- See inline doumentation._
resolveElement(val:String|HTMLElement) _- Resolves a HTMLElement, supports >>> as shadow dom selector._
adjustableInputNumbers(el:InputElement, mapper:Function) _- Creates the possibility to change the numbers in an inputfield via mouse scrolling.
The mapper function takes three arguments: the matched number, an multiplier and the index of the match._

Use this utils carefully, it's not for sure that they will stay forever!

Static properties

version _- The current version._
I18N_DEFAULTS _- i18n default values._
DEFAULT_OPTIONS _- Default options (Do not override this property itself, only change properties of it!)._

FAQ

How do I initialize multiple pickr's? Can I access the instance via class or id?


No, you can't. You need to keep track of your instance variables - pickr is (not yet) a web-component.
The best option would be to create new elements via document.createElement and directly pass it as el.
example.

I want to use pickr in a form, how can I do that?


You can use useAsButton: true and pass a reference (or selector) of your input-element as el. Then you can update the input-element whenever a change was made. example.

I want to update options after mounting pickr, is that possible?


Unfortunately not. The core-code of this project is rather old (over 2 years), and I made it in my early js-days - the widget is not able to dynamically re-render itself in that way.
You have to destroy and re-initialize it.

Contributing

If you want to open a issue, create a Pull Request or simply want to know how you can run it on your local machine, please read the Contributing guide.