Skip to content
thednp edited this page Mar 24, 2022 · 52 revisions

ColorPicker

Creates a new ColorPicker instance given the appropriate markup. The constructor comes with many properties, event listeners and other tools, however on this page we're documenting mostly the most important properties and public methods.

On initialization, the constructor will create the additional elements for the two dropdown elements: one for the ColorPicker itself and one for the colour presets (if enabled).

Parameters

  • target: HTMLInputElement | string - an <input> element or selector string;
  • config: Object | undefined - the instance options are all optional.

Options:

  • componentLabels: allows you to customize or translate all internal component labels for multi-language applications,
  • colorLabels: allows you to customize or translate colour appearance labels,
  • format: sets the instance colour format, the default value is 'rgb',
  • colorPresets: allows you to set a number of colours, separated by comma or a ColorPalette to be used as presets, the default value is false,
  • colorKeywords: allows you to set a number of explicit defaults (EG: transparent, initial, etc) and servers a very specific function, the default value is false.

Markup

ColorPicker comes with a wide range of DATA API attributes, to configure everything to your need.

For WAI-ARIA compliance, the ColorPicker allows you to set all component labels and color names via DATA API and JSON strings, for instance this is how to add configure another language with ColorPicker:

<label for="picker">Some label relevant to your context</label>
<div class="color-picker">
  <input type="text" value="rgb(0,160,10)" class="color-preview btn-appearance" name="picker" id="picker"
   data-function="color-picker"  
   data-format="rgb"
   data-component-labels='{"pickerLabel": "Custom Colour Picker", ...}'
   data-color-labels="white, black, ....">
</div>
  • The data-function="color-picker" attribute is the default selector used by the init callback;
  • The data-component-labels attribute sets all the labels of the HTML markup elements.
  • The data-color-labels sets the colour appearance labels, very useful for accessibility purposes. The value you set for the data-color-labels must match the amount (17), order and meaning.
  • The autocomplete="off" and spellcheck="false" attributes could prove useful for both aesthetics and functionality.
  • Note: the markup is important, you must keep color-picker, btn-appearance and color-preview class names for layout consistency.

JavaScript

When using the ColorPicker, an initialization script is required, you can use the following:

import ColorPicker from '@thednp/color-picker';

// initialize a specific `<input>`
let myPicker = new ColorPicker('#myPicker');

// initialize all targets with the DATA API
const { init, selector } = ColorPicker;
[...document.querySelectorAll(selector)].forEach(init);

Static Methods

The perfect time to talk about the static methods, they're all related to initialization.

init

The initialization callback that makes use of the internally defined [data-function="color-picker"] selector and enable initialization for multiple <input> targets at once.

Example:

const { init, selector } = ColorPicker;
[...document.querySelectorAll(selector)].forEach(init);

getInstance

Returns the ColorPicker instance for a given target.

const mySpecificInstance = ColorPicker.getInstance(mySpecificTarget);

// do some dew with private methods
mySpecificInstance.showPicker();

// or check some specific property
if (mySpecificInstance.isDark) {
  // do something about that
}

Getters & Setters

set value

Sets a new instance.value and is mostly internally used to reference the string value of the target <input>.

const myInstance = new ColorPicker('selector');

myInstance.value = 'red';

get value

Returns the instance.value representing the CSS valid string format of the current colour.

When things get messy, you can always check your:

const myInstance = new ColorPicker('selector');

if (myInstance.value === '#ff0000') {
  console.log('this color is RED');
}

get hasNonColor

Check if the colour presets include any non-color value, specifically transparent, currentColor, inherit, initial or revert. This is important and useful for cases where your target input must always use CSS valid string colour format values that need to be compatible with SCSS/LESS/postCSS mixins, compilers will simply not be able to do darken(revert).

const myInstance = new ColorPicker('selector');

if (!myInstance.hasNonColor) {
  // do something about it, perhaps set another color value
  myInstance.value = '#000';
}

get isCE

Check if the parent of the target is a ColorPickerElement instance. When initializing a new instance, ColorPicker needs to know where DATA API configuration comes from.

const myInstance = new ColorPicker('selector');

if (myInstance.isCE) {
  console.log('this instance is a ColorPickerElement instance');
}

get hex

Returns hexadecimal value of the current colour.

const myInstance = new ColorPicker('selector');

const { hex } = myInstance;

get hsv

Returns the current colour in {h,s,v,a} object format.

const myInstance = new ColorPicker('selector');

const { hsv } = myInstance;

get hsl

Returns the current colour in {h,s,l,a} object format.

const myInstance = new ColorPicker('selector');

const { hsl } = myInstance;

get rgb

Returns the current colour in {r,g,b,a} object format.

const myInstance = new ColorPicker('selector');

const { rgb } = myInstance;

get brightness

Returns the current colour brightness in the [0-255] range.

const myInstance = new ColorPicker('selector');

const { brightness } = myInstance;

get luminance

Returns the current colour luminance in the [0-1] range.

const myInstance = new ColorPicker('selector');

const { luminance } = myInstance;

get isDark

Checks if the current colour requires a light text color by checking if the brightness level is less then 120 and transparency more than 33%.

const myInstance = new ColorPicker('selector');

const { isDark } = myInstance;

get isValid

Checks if the target input current value is a valid colour.

const myInstance = new ColorPicker('selector').isValid;

// => boolean

Private Methods

ColorPicker.showPicker

Description

Shows the ColorPicker dropdown.

Returns - void.

ColorPicker.togglePicker

Description

Toggles the visibility of the ColorPicker presets menu.

Returns - void.

ColorPicker.show

Description

Shows the ColorPicker dropdown.

Returns - boolean.

ColorPicker.hide

Description

Hides any ColorPicker dropdown.

Returns - boolean.

ColorPicker.hide

Description

Hides any visible ColorPicker dropdown, either the colour picker itself or the presets menu.

Parameters

  • focusPrevented: boolean | undefined - when false or unset, the target input will be focused.

Returns - boolean.

ColorPicker.dispose

Description

Removes ColorPicker from target <input>.

Returns - void.

Color

The Color class returns a new Color instance and is a fork of the excellent TinyColor optimized for ColorPicker. It inherits the powerful TinyColor permissive regular expressions as well as a small new utility to convert web safe colors to hexadecimal format.

Usage

import Color from "@thednp/color-picker/src/js/color";

const myHEXColor = new Color('red', 'hex');
const myRGBColor = new Color('hsv 120 80 50', 'rgb');
const myHSLColor = new Color('069', 'hsl');

Color.constructor()

Description

Creates a new Color instance and returns it.

Parameters

  • input: HTMLInputElement | HTMLElement,
  • format: string | hex | rgb | rgba | hsl | hsla

Returns - a new Color instance.

Color.get.isValid

Description

Checks if the current input value is a valid colour.

Returns - boolean

Color.get.isDark

Description

Checks if the current input value is a dark colour, useful when you want to determine the right text colour over the background colour.

Returns - boolean

Color.get.luminance

Description

Returns the perceived luminance of a color, in the 0-1 range.

Returns - number

Color.get.brightness

Description

Returns the perceived brightness of a color, in the 0-255 range.

Returns - number

Color.toRgb

Description

Returns the RGBA colour as a {r, g, b, a} object, representing the red, green, blue and alpha components.

Returns - object

Color.toRgbString

Description

Returns the RGBA component values concatenated into a CSS valid string in RGB/RGBA format.

Returns - string

Color.toHex

Description

Returns the hexadecimal value of the current colour.

Returns - string

Color.toHexString

Description

Returns the hexadecimal value of the current colour as a CSS valid string.

Returns - string

Color.toHsv

Description

Returns the HSVA color as a {h, s, v, a} object, or hue, saturation, brightness value and alpha channel. As browsers don't currently support the HSV colour format, this method is internally used for rendering the <canvas> elements of the ColorPicker.

Returns - object

Color.toHsl

Description

Returns the HSLA color as a {h, s, l, a} object, representing the hue, saturation, lightness and alpha components.

Returns - object

Color.toHslString

Description

Returns the HSLA values concatenated into a CSS valid string value in HSL/HSLA format.

Returns - string

Color.setAlpha

Description

Sets the alpha value of the current colour.

Parameters

  • alpha: number a new alpha value in the [0-1] range.

Returns - the current Color instance

Color.saturate

Description

Saturate the colour with a given amount.

Parameters

  • amount: number a new alpha value in the [0-100] range.

Returns - a new Color instance

Color.desaturate

Description

Desaturate the colour with a given amount.

Parameters

  • amount: number a new alpha value in the [0-100] range.

Returns - a new Color instance

Color.greyscale

Description

Desaturate the colour with the maximum amount.

Returns - a new Color instance

Color.toString()

Description

Returns the color value in CSS valid string in the format configured on initialization.

Returns - string

ColorPickerElement

Creates a new <color-picker> element and handles connectedCallback and disconnectedCallback callbacks. The class creates a single <slot> element to which all elements generated in the LightDOM are connected.

Inject Element into the DOM

To use the ColorPickerElement custom element, all DATA API options are to be set for the <color-picker> custom element itself:

<label for="myPicker">Color Label</label>
<color-picker data-format="hsl" data-value="#069">
  <input id="myPicker" name="myPicker" class="color-preview btn-appearance">
</color-picker>

Create a new instance

On initialization, the ColorPickerElement class will generate the basic markup, but before the element is appended, we can provide instance configuration options via DATA API:

import ColorPickerElement from '@thednp/color-picker/src/color-picker-element';

// initialize the CustomElement
const myPicker = new ColorPickerElement();

// set DATA API
myPicker.setAttribute('data-format', 'hsl');
myPicker.setAttribute('data-id', 'ADD_YOUR_UNIQUE_ID');
myPicker.setAttribute('data-value', 'rgb(150 0 150 / 0.8)');
myPicker.setAttribute('data-label', 'Some Label');
myPicker.setAttribute('data-color-keywords', 'false'); // see configuration options above
myPicker.setAttribute('data-color-presets', 'false'); // see configuration options above
myPicker.setAttribute('data-color-names', 'SET_THE_COLOR_NAMES_TRANSLATED_IN_YOUR_LANGUAGE_HERE');

// append the element
// connectedCallback() is now triggered
document.getElementById('SOME_CONTEXT').append(myPicker);

ColorPalette

A light utility class that returns an ideal object needed to create custom colour palettes, but most importantly the colours themselves properly computed and sorted, just to fill a perfect grid.

Parameters

  • hue: number in [0-360] range - the starting hue from which all colour palettes are computed; the default value is 0 (zero), however, while this parameter is first, it's an optional value;
  • hueSteps: number in [5-24] range works best - the amount of colour palettes to generate;
  • lightSteps: number in [5-12] range works best - the amount of colour tints each palette has.

White the last two parameters have no maximum limit, for performance and layout consistency reasons, it would be best to use values in the recommended range.

Returns

  • an object with the following structure:
{
 hue: Number,
 hueSteps: Number,
 lightSteps: Number,
 colors: String[]
}

Examples

You can either provide all parameters:

const my24x12Palette = new ColorPalette(270, 24, 12);

// => { hue: 270, hueSteps: 24, lightSteps: 12, colors: ['#460000', '#740000', ...286 more colors] }

Or only provide the amount of hueSteps and lightSteps:

const my24x12Palette = new ColorPalette(24, 12);

// => { hue: 0, hueSteps: 24, lightSteps: 12, colors: ['#460000', '#740000', ...286 more colors] }
Clone this wiki locally