Skip to content
thednp edited this page Sep 26, 2024 · 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 serves 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 public 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

get appearance

Returns the colour appearance, usually the closest colour name for the current value.

<input id="myInput" value="rgb(255,0,0)">
const myColorAppearance = new ColorPicker('#myInput').appearance;

// => red

Public 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();

ColorPicker Custom Event

Every time the value of the ColorPicker is changed, a CustomEvent called colorpicker.change is triggered.

targetInput.addEventListener('colorpicker.change', e => {
  // do something with the value
  console.log(e.target.value);
})