Skip to content
thednp edited this page Mar 28, 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.

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 value:

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 the hexadecimal value of the current colour.

const myInstance = new ColorPicker('selector');

// make use of object deconstruction
const { hex } = myInstance;

console.log(`Hexadecimal ${hex}`);

get hsv

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

const myInstance = new ColorPicker('selector');

// make use of object deconstruction
const { h, s, v } = myInstance.hsv;

console.log(`hsv(${h}, ${s}, ${v})`);

get hsl

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

const myInstance = new ColorPicker('selector');

// make use of object deconstruction
const { h, s, l } = myInstance.hsl;

console.log(`hsl(${h}, ${s}, ${l})`);

get rgb

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

const myInstance = new ColorPicker('selector');

// make use of object deconstruction
const { r, g, b } = myInstance.rgb;

console.log(`rgb(${r}, ${g}, ${b})`);

get brightness

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

const myInstance = new ColorPicker('selector');

if (myInstance.brightness > 120) {
  console.log('your colour is above average brightness')
}

get luminance

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

const myInstance = new ColorPicker('selector');

if (myInstance.luminance > 0.3) {
  console.log('your colour is mostly distinguishable from black')
}

get isDark

Checks if the current colour requires a light text color by measuring the brightness level to be less then 120 and alpha (transparency) more than 33%.

const myInstance = new ColorPicker('selector');

if (myInstance.isDark) {
  // do some text color toggle
}

get isValid

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

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

// => boolean

Private Methods

The ColorPicker component comes with many properties and methods, most of them are internally used, but we'll focus mostly on the following:

showPicker

Shows the ColorPicker dropdown.

const myInstance = new ColorPicker('selector');

myInstance.showPicker();

togglePicker

Toggles the visibility of the ColorPicker dropdown. If the dropdown is visible, it will be hidden or shown otherwise.

const myInstance = new ColorPicker('selector');

myInstance.togglePicker();

toggleMenu

Toggles the visibility of the ColorPicker presets menu. If the dropdown is visible, it will be hidden or shown otherwise.

const myInstance = new ColorPicker('selector');

myInstance.toggleMenu();

hide

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

Parameters

  • focusPrevented: boolean | undefined - when false or undefined, the target input will be focused.
const myInstance = new ColorPicker('selector');

myInstance.hide();

update

Any time you've changed anything within the ColorPicker you can also update the instance.

const myInstance = new ColorPicker('selector');

// let's say we change the colour
myInstance.color = new ColorPicker.Color({r: 150, g: 0, b: 150});

// call the update
myInstance.update();

dispose

Removes ColorPicker from target <input>. When called, it will remove all additional element generated on initialization such as the dropdown elements, but will also reset the <input> styling.

const myInstance = new ColorPicker('selector');

myInstance.dispose();

Color

The Color class returns a new Color instance. The class is an ES6+ flavored fork of the excellent TinyColor but optimized for ColorPicker and features an improved permissive regular expressions, new features as well as a small new utility to convert web safe colors to RGB.

Quick Usage

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

// provide a web colour, the constructor will determine
// !IMPORTANT - this requires a web browser environment
const myHEXColor = new Color('red', 'hex');
// => { r: 250, g: 0, b: 0, a: 1, ok: true, originalInput: 'red', ...}

// provide a CSS4 valid string
const myRGBColor = new Color('hwb(15deg 0% 0% / 90%)', 'rgb');
// => { r: 255, g: 63.75, b: 0, a: 0.9, originalInput: 'hwb(15deg 0% 0% / 90%)', …}

// provide a CSS like string of specific format
const myRGBColor = new Color('hsv 120 80 50', 'rgb');
// => { r: 25.5, g: 127.5, b: 25.5, a: 1, ok: true, originalInput: 'hsv 120 80 50', ...}

// provide a number
const myHSLColor = new Color('075', 'hsl');
// => {r: 0, g: 119, b: 85, a: 1, originalInput: '075', ...}

Parameters

  • input: object | string - a colour in either CSS valid format or RGB, HSL, HWB or HEX object,
  • format: undefined | hex | rgb | rgb | hsl | hwb.

Color Getters & Setters

get isValid

Checks if the current input value is a valid colour.

const isValidColor = new Color('wombat').isValid;

// => false

const isValidColor = new Color('red').isValid;

// => true

get isDark

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

const isDarkColor = new Color('red').isDark;

// => true

const isDarkColor = new Color('yellow').isDark;

// => false

get luminance

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

const luminance = new Color('red').luminance;

// => 0.2126

get brightness

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

const brightness = new Color('red').brightness;

// => 76.245

Private Methods

toRgb

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

const rgb = new Color('red').toRgb();

// => { r: 255, g: 0, b: 0, a: 1 }

toRgbString

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

const rgbString = new Color('red').toRgbString();

// => rgb(255, 0, 0)

toRgbCSS4String

Returns the RGBA component values concatenated into a CSS4 Module valid string in specific format.

const rgbString = new Color('rgba(255, 0, 0, 0.5)').toRgbCSS4String();

// => rgb(255 0 0 / 50%)

toHex

Returns the hexadecimal value of the current colour.

const hex = new Color('red').toHex();

// => ff0000

toHexString

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

const hexString = new Color('red').toHexString();

// => #ff0000

toHwb

Returns the HWB value of the current colour.

const hwb = new Color('red').toHwb();

// => {h:0, w: 0, b: 0, a: 1}

toHwbString

Returns the HWB value of the current colour as a CSS valid string. The HWB format is part of the CSS4 Module and only supports CSS4 string in all current modern browsers.

const hwbString = new Color('rgba(255, 0, 0, 0.5)').toHwbtring();

// => hwb(0% 0% 0% / 50%)

toHsv

Returns the HSVA colour as a {h, s, v, a} object, or hue, saturation, brightness value and alpha channel. This method is internally used for the rendering the ColorPicker controls.

const hsv = new Color('red').toHsv();

// => {h: 0, s: 1, v: 1, a: 1}

The Color class doesn't provide a toHsvString method as current browsers don't provide support for the HSV format.

toHsl

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

const hsl = new Color('red').toHsl();

// => {h: 0, s: 1, l: 0.5, a: 1}

toHslString

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

const hslString = new Color('red').toHslString();

// => hsl(0, 100%, 50%)

toHslCSS4String

Returns the HSLA values concatenated into a CSS4 Module valid string value in specific format.

const hslString = new Color('rgb(100%, 0%, 0%, 50%)').toHslCSS4String();

// => hsl(0 100% 50% / 50%)

setAlpha

Sets the alpha value of the current colour.

Parameters

  • alpha: number a new alpha value in the [0-1] range.
const rgbAColor = new Color('red').setAlpha(0.5).toRgbString();

// => rgba(255, 0, 0, 0.5)

saturate

Saturate the colour with a given amount.

Parameters

  • amount: number a saturation value in the [0-100] range.
const saturatedColor = new Color('#e61919').saturate(10).toString();

// => #ff0000

desaturate

Desaturate the colour with a given amount.

Parameters

  • amount: number a saturation value in the [0-100] range.
const desaturatedColor = new Color('#ff0000', 'hex').desaturate(10).toString();

// => #e61919

greyscale

Desaturate the colour with the maximum amount.

const greyscaledColor = new Color('#ff0000', 'hex').greyscale().toString();

// => #808080

lighten

Increase the colour lightness by a given amount.

Parameters

  • amount: number a lightness value in the [0-100] range.
const lighterColor = new Color('#ff0000', 'hex').lighten(10).toString();

// => #ff3333

darken

Decrease the colour lightness by a given amount. Parameters

  • amount: number a lightness value in the [0-100] range.
const darkerColor = new Color('#ff0000', 'hex').darken(10).toString();

// => #cc0000

toString

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

Parameters

  • allowShorthand: boolean | undefined - when true, if the format setting is hex and the output matches a certain set of conditions, the shorthand hexadecimal value is the return of this method.
const hexColor = new Color('#006699', 'hex').toString(true);

// => #069

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] }

Initialize a ColorPicker instance with your custom colour palette:

const my24x12Palette = new ColorPalette(24, 12);

const myCPInstance = new ColorPicker('targetSelector', {colorPresets: my24x12Palette});

Clone this wiki locally