vmdao / pickr

🍭 Flat, simple, responsive and hackable Color-Picker library. No dependencies, no jQuery. Compatible with all CSS Frameworks e.g. Bootstrap, Materialize. Supports alpha channel, rgba, hsla, hsva and more!

Home Page:https://simonwep.github.io/pickr

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Logo

Flat, Simple, Hackable Color-Picker.

gzip size brotli size Build Status Download count No dependencies JSDelivr download count Current version Support me


Demo


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
  • Shadow-dom support

Themes

Classic Monolith Nano
Classic theme Monolith Nano

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:

$ npm install @simonwep/pickr

Install via yarn:

$ yarn add @simonwep/pickr

Include code and style:

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

// Modern or es5 bundle
import Pickr from '/node_modules/@simonwep/pickr/dist/pickr.min';      
import Pickr from '/node_modules/@simonwep/pickr/dist/pickr.es5.min'; 

Browser

jsdelivr:

<!-- One of the following themes -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.min.css"/> <!-- 'classic' theme -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.monolith.min.css"/> <!-- 'monolith' theme -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.nano.min.css"/> <!-- 'nano' theme -->

<!-- Modern or es5 bundle -->
<script src="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.es5.min.js"></script>

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

// Simple example, see optional options for more configuration.
const pickr = Pickr.create({
    el: '.color-picker',
    
    swatches: [
        'rgba(244, 67, 54, 1)',
        'rgba(233, 30, 99, 0.95)',
        'rgba(156, 39, 176, 0.9)',
        'rgba(103, 58, 183, 0.85)',
        'rgba(63, 81, 181, 0.8)',
        'rgba(33, 150, 243, 0.75)',
        'rgba(3, 169, 244, 0.7)',
        'rgba(0, 188, 212, 0.7)',
        'rgba(0, 150, 136, 0.75)',
        'rgba(76, 175, 80, 0.8)',
        'rgba(139, 195, 74, 0.85)',
        'rgba(205, 220, 57, 0.9)',
        'rgba(255, 235, 59, 0.95)',
        'rgba(255, 193, 7, 1)'
    ],

    components: {

        // Main components
        preview: true,
        opacity: true,
        hue: true,

        // Input / output Options
        interaction: {
            hex: true,
            rgba: true,
            hsla: true,
            hsva: true,
            cmyk: true,
            input: true,
            clear: true,
            save: true
        }
    }
});

Events

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

Event Description Arguments
init Initialization done - pickr can be used PickrInstance
save User clicked the save / clear button HSVaColorObject | null, PickrInstance
change Color has changed (but not saved). Also fired on swatchselect HSVaColorObject, PickrInstance
swatchselect User clicked one of the swatches HSVaColorObject, PickrInstance

Example:

pickr.on('init', (...args) => {
    console.log('init', args);
}).on('save', (...args) => {
    console.log('save', args);
}).on('change', (...args) => {
    console.log('change', args);
}).on('swatchselect', (...args) => {
    console.log('swatchselect', args);
});

Options

const pickr = new Pickr({

    // Selector or element which will be replaced with the actual color-picker.
    // Can be a HTMLElement.
    el: '.color-picker',
    
    // Which theme you want to use. Can be 'classic', 'monolith' or 'nano'
    theme: 'classic',
    
    // Nested scrolling is currently not supported and as this would be really sophisticated to add this 
    // it's easier to set this to true which will hide pickr if the user scrolls the area behind it.
    closeOnScroll: false,

    // Custom class wich gets added to the pickr-app. Can be used to apply custom styles.
    appClass: 'custom-class',

    // Using the 'el' Element as button, won't replace it with the pickr-button.
    // If true, appendToBody will also be automatically true.
    useAsButton: false,
    
    // If true pickr won't be fixed and instead append after the in el resolved element.
    // Setting this to true will also set showAlways to true. It's possible to hide it via .hide() anyway.
    inline: false,
    
    // Defines the direction in which the knobs of hue and opacity can be moved.
    // 'v' => opacity- and hue-slider can both only moved vertically.
    // 'hv' => opacity-slider can be moved horizontally and hue-slider vertically.
    // Can be used to apply custom layouts
    sliders: 'v',

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

    // If set to false it would directly apply the selected color on the button and preview.
    comparison: true,
    
    // Default color
    default: 'fff',
    
    // Optional color swatches. null by default which means it's disabled.
    // Types are all these allowed which can be used in pickr e.g. hex, hsv(a), hsl(a), rgb(a), cmyk or a name like 'magenta'
    swatches: ['#F44336', '#E91E63', '#9C27B0', '#673AB7'],

    // Default color representation.
    // Valid options are `HEX`, `RGBA`, `HSVA`, `HSLA` and `CMYK`.
    defaultRepresentation: 'HEX',

    // Option to keep the color picker always visible. You can still hide / show it via
    // 'pickr.hide()' and 'pickr.show()'. The save button keeps his functionality, so if
    // you click it, it will fire the onSave event.
    showAlways: false,

    // Close pickr with this specific key.
    // Default is 'Escape'. Can be the event key or code.
    closeWithKey: 'Escape',

    // Defines the position of the color-picker. 
    // Any combinations of top, left, bottom or right with one of these optional modifiers: start, middle, end
    // Examples: top-start / right-end
    // If clipping occurs, the color picker will automatically choose its position.
    position: 'bottom-middle',

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

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

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

        preview: true, // Left side color comparison
        opacity: true, // Opacity slider
        hue: true,     // Hue slider

        // Bottom interaction bar, theoretically you could use 'true' as propery.
        // But this would also hide the save-button.
        interaction: {
            hex: true,  // hex option  (hexadecimal representation of the rgba value)
            rgba: true, // rgba option (red green blue and alpha)
            hsla: true, // hsla option (hue saturation lightness and alpha)
            hsva: true, // hsva option (hue saturation value and alpha)
            cmyk: true, // cmyk option (cyan mangenta yellow key )

            input: true, // input / output element
            clear: true, // Clear button
            save: true   // Save button
        },
    },

    // Button strings, brings the possibility to use a language other than English.
    strings: {
       save: 'Save',  // Default for save button
       clear: 'Clear' // Default for clear button
    }
});

Selection through a Shadow-DOM

Example setup:

<div class="entry">
  #shadow-root 
    <div class="innr">
       <div class="another">
         #shadow-root 
           <div class="pickr"></div>
       </div>
    </div>
</div>

To select the .pickr element you can use the custom >> shadow-dom-selector in el:

el: '.entry >> .innr .another >> .pickr'

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 cymk array.
  • hsva.clone() - Clones the color object.

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

hsva.toRGBA(); // Returns [r, g, b, a]
hsva.toRGBA().toString(); // Returns rgba(r, g, b, a)

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(representation:String, 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) - Appends an eventlistener to the given corresponding event-name (see section Events), returns the pickr instance so it can be chained.
  • pickr.off(event:String, cb:Function) - Removes an eventlistener from the given corresponding event-name (see section Events), returns the pickr instance so it can be chained.
  • pickr.show() - Shows the color-picker, returns instance.
  • pickr.hide() - Hides the color-picker, returns instance.
  • pickr.disable() - Disables pickr and adds the disabled class to the button, returns instance.
  • pickr.enable() - Enables pickr and removes the disabled class from the button, returns instance.
  • pickr.isOpen() - Returns true if the color picker is currently open.
  • pickr.getRoot():HTMLElement - Returns the root DOM-Element of the color-picker.
  • pickr.getColor():HSVaColor - Returns the current HSVaColor object.
  • pickr.destroy():HSVaColor - Destroy's all functionality.
  • pickr.destroyAndRemove():HSVaColor - Destroy's 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.applyColor(silent:Boolean) - 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) - Removes a color from the swatch palette by its index.

Static methods

Pickr

  • 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.
  • removeAttribute(el:HTMLElement, name:String) - Removes an attribute from a HTMLElement and returns the value.
  • createFromTemplate(str:String) - See inline doumentation.
  • 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!

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.

About

🍭 Flat, simple, responsive and hackable Color-Picker library. No dependencies, no jQuery. Compatible with all CSS Frameworks e.g. Bootstrap, Materialize. Supports alpha channel, rgba, hsla, hsva and more!

https://simonwep.github.io/pickr

License:MIT License


Languages

Language:JavaScript 67.1%Language:CSS 29.0%Language:HTML 3.9%