Modular JavaScript Color & Gradient Picker – ew-color-picker

Category: Color , Javascript | November 25, 2026
Authoreveningwater
Last UpdateNovember 25, 2026
LicenseMIT
Views0 views
Modular JavaScript Color & Gradient Picker – ew-color-picker

ew-color-picker is a modular JavaScript color picker library for selecting solid colors and editing CSS gradients.

It supports HEX, RGB, and HSL input with adjustable opacity and lets you choose or replace the picker controls with plugins.

Features

  • Four panel sizes for desktop and mobile layouts.
  • Horizontal or vertical hue and opacity sliders.
  • Custom color palettes with optional disabled swatches.
  • Draggable gradient stops, angles, radial and conic positions, and repeating gradients.
  • Screen color sampling in browsers that support the EyeDropper API.
  • One-click color copying to the clipboard.
  • Clear and confirmation buttons with customizable labels.
  • Automatic panel positioning and support for mounting outside clipped containers.
  • Works with vanilla JavaScript, Vue and React.

How to Use It

Basic Usage

Download and load the necessary JS & CSS files:

<link rel="stylesheet" href="index.css">
<link rel="stylesheet" href="input-number.css">
<script src="ew-color-picker.js"></script>

Create an empty DIV element for your color picker:

<div id="color-picker"></div>

Initialize the color picker:

const picker = new ewColorPicker({
  el: '#color-picker',
  defaultColor: '#16856b',
  clearText: 'Reset',
  sureText: 'Apply'
});

Install with npm

npm install @ew-color-picker/ew-color-picker @ew-color-picker/style

Use the same #color-picker element with the following module imports:

import ewColorPicker from '@ew-color-picker/ew-color-picker';
import '@ew-color-picker/style/dist/index.css';
import '@ew-color-picker/style/dist/input-number.css';
const picker = new ewColorPicker({
  el: '#color-picker',
  defaultColor: '#16856b'
});

Connect the Picker to a Live Preview

Use change to preview each adjustment and sure to capture the confirmed color. Add these elements alongside the picker:

<div id="preview" style="width: 240px; height: 100px; background: #16856b;"></div>
<p>Current color: <output id="color-value">#16856b</output></p>
<p>Confirmed color: <output id="saved-color">#16856b</output></p>
const preview = document.querySelector('#preview');
const output = document.querySelector('#color-value');
const saved = document.querySelector('#saved-color');
picker.on('change', color => {
  preview.style.backgroundColor = color;
  output.textContent = color;
});
picker.on('sure', color => {
  saved.textContent = color;
});

Configure a Compact Picker

Replace the Basic Usage instance with this configuration to fit the picker inside a narrow settings panel.

Mount the popup in document.body to escape clipping by scroll containers.

const picker = new ewColorPicker({
  el: '#color-picker',
  defaultColor: '#16856b',
  panelMode: 'mini',
  hueDirection: 'horizontal',
  alphaDirection: 'horizontal',
  predefineColor: [
    '#16856b', '#e3a532', '#c74343',
    { color: '#20252b', disabled: true }
  ],
  autoPanelPosition: true,
  panelPlacement: 'bottom-start',
  appendTo: document.body,
  clearText: 'Reset',
  sureText: 'Apply',
  copyColorText: 'Copy color',
  copiedText: 'Copied'
});

Create a CSS Gradient Editor

Keep the Panel plugin enabled to edit the color of the selected stop. If you are using the browser build from Basic Usage, copy select.css, tooltip.css, and checkbox.css from @ew-color-picker/style/dist/ and load them alongside the first two stylesheets.

<link rel="stylesheet" href="select.css">
<link rel="stylesheet" href="tooltip.css">
<link rel="stylesheet" href="checkbox.css">
<div id="gradient-picker"></div>
<div id="gradient-preview" style="height: 120px;"></div>
<output id="gradient-css"></output>
<script>
  const gradientPreview = document.querySelector('#gradient-preview');
  const gradientOutput = document.querySelector('#gradient-css');
  function applyGradient(css) {
    gradientPreview.style.background = css;
    gradientOutput.textContent = css;
  }
  const gradientPicker = new ewColorPicker({
    el: '#gradient-picker',
    showGradient: true,
    gradient: 'linear-gradient(120deg, #16856b 0%, #e3a532 100%)',
    gradientChange: applyGradient,
    clearText: 'Reset',
    sureText: 'Apply'
  });
  applyGradient(gradientPicker.plugins.ewColorPickerGradient.getGradient());
</script>

For npm projects, use the same markup and initialization in your module. Add the following imports to the Basic Usage npm imports:

import '@ew-color-picker/style/dist/select.css';
import '@ew-color-picker/style/dist/tooltip.css';
import '@ew-color-picker/style/dist/checkbox.css';

Import Only the Controls You Need

For a smaller custom build, install the core and the plugins that supply the swatch, saturation panel, hue slider, text field, and buttons.

npm install @ew-color-picker/core @ew-color-picker/style @ew-color-picker/box @ew-color-picker/panel @ew-color-picker/hue @ew-color-picker/input @ew-color-picker/button
import ewColorPicker from '@ew-color-picker/core';
import Box from '@ew-color-picker/box';
import Panel from '@ew-color-picker/panel';
import Hue from '@ew-color-picker/hue';
import Input from '@ew-color-picker/input';
import Button from '@ew-color-picker/button';
import '@ew-color-picker/style/dist/index.css';
ewColorPicker.use(Box).use(Panel).use(Hue).use(Input).use(Button);
const picker = new ewColorPicker({
  el: '#color-picker',
  defaultColor: '#16856b',
  clearText: 'Reset',
  sureText: 'Apply'
});

Vue and React Integration

Vue:

npm install @ew-color-picker/vue @ew-color-picker/style
<script setup>
import { ref } from 'vue';
import { EwColorPicker } from '@ew-color-picker/vue';
import '@ew-color-picker/style/dist/index.css';
import '@ew-color-picker/style/dist/input-number.css';
const color = ref('#16856b');
</script>
<template>
  <EwColorPicker v-model="color" :options="{ panelMode: 'small' }" />
</template>

React:

npm install @ew-color-picker/react @ew-color-picker/style
import { useState } from 'react';
import { EwColorPicker } from '@ew-color-picker/react';
import '@ew-color-picker/style/dist/index.css';
import '@ew-color-picker/style/dist/input-number.css';
export default function ColorField() {
  const [color, setColor] = useState('#16856b');
  return <EwColorPicker value={color} onChange={setColor}
    options={{ panelMode: 'small' }} />;
}
Vue prop or eventDescription
modelValueOptional color string; bound through v-model.
optionsCore picker options, default {}; the wrapper supplies el.
update:modelValue, changeCurrent color string.
sureConfirmed color string.
clear, destroyNo arguments.
toggleBoolean panel state.
mode-changeInput mode string.
React propDescription
valueOptional controlled color string.
optionsCore options; the wrapper supplies el.
onChange(color), onSure(color)Changed or confirmed color.
onClear()Clear action.
onToggle(open)Boolean panel state.
onModeChange(mode)Input mode string.
className, styleHost class string and React CSSProperties object.

Both wrappers expose getColor(), setColor(color), openPicker(), closePicker(), and getInstance() through a ref. They read options at mount time. Use getInstance().updateOptions() to change configuration. To clear the picker programmatically, call setColor('') through the ref.

Constructor and Factory

SignatureDescription
new ewColorPicker(options?)An options object; supply el to mount automatically.
new ewColorPicker(el, options?)A selector string or HTMLElement followed by an optional configuration object.
createEwColorPicker(options?)Factory exported by the all-in-one and unscoped ew-color-picker packages; accepts an options object, selector, or HTMLElement and returns a picker instance.

Configuration Options

Color and appearance

  • el (string or HTMLElement): Mount target; the fallback container is document.body.
  • defaultColor (string, default ''): Initial color and reset value for the Clear button.
  • disabled (boolean, default false): Disables picker controls.
  • readonly (boolean, default false): Prevents the trigger swatch from opening or closing the picker.
  • size (string, number, or { width, height }, default 'normal'): Trigger size; presets mini, small, normal, medium, and large correspond to 20, 24, 32, 36, and 40px. Numbers represent pixels; CSS size strings are accepted.
  • panelMode ('mini', 'small', 'medium', or 'large', default 'large'): Scales the picker panel and its controls.
  • predefineColor (Array<string | { color: string; disabled?: boolean }>, default []): Preset swatches; an empty array hides the palette.
  • defaultMode ('hex', 'rgb', or 'hsl'): Defaults to rgb when the Alpha plugin is present; otherwise hex.
  • hueDirection, alphaDirection ('vertical' or 'horizontal', both default 'vertical'): Slider orientation.
  • boxNoColorIcon, boxHasColorIcon (string, both default ''): Custom HTML for the empty and filled swatch icons. Pass trusted markup.
  • className (string, default ''): Extra class on the trigger swatch.
  • style (string or Record<string, string>, default ''): Inline styles for the trigger swatch.
  • prefix (string, default 'ew-'): Generated CSS class prefix; match the compiled stylesheet prefix.
panelModePanel dimensions (width x height)
mini180 x 140px; 202px wide with both sliders horizontal.
small220 x 150px; 247px wide with both sliders horizontal.
medium250 x 165px; 281px wide with both sliders horizontal.
large285 x 180px; 320px wide with both sliders horizontal.

Panel behavior

  • isClickOutside (boolean, default true): Closes the panel when clicking outside it.
  • autoPanelPosition (boolean, default false): Automatically positions the panel relative to the Box trigger. For a custom trigger, use appendTo with panelPlacement.
  • panelPlacement (string, default 'bottom'): Accepts top-start, top, top-end, left-start, left, left-end, right-start, right, right-end, bottom-start, bottom, and bottom-end.
  • appendTo (string or HTMLElement, default undefined): Moves the panel to another container with fixed positioning and scroll/resize updates. Uses the host element as the anchor if the built-in swatch is absent.
  • boundary (string, HTMLElement, or null, default null): Constrains automatic placement to the visible bounds of a container; null uses the viewport.
  • togglePickerAnimation (string, default 'default'): Choose default for instant toggling, height for sliding, or opacity for fading.
  • pickerAnimationTime (number, default 200): Animation duration in milliseconds, capped at 10000.

Controls and labels

OptionControl
hasBoxTrigger swatch.
hasPanelSaturation/value panel.
hasInputText color field.
hasClearClear button.
hasSureConfirmation button.
hueHue slider.
alphaOpacity slider.
showButtonBoth action buttons.
showColorModeHEX/RGB/HSL switcher.
showInputNumberInputNumber plugin’s own input; ColorMode channel inputs are unaffected.
showEyedropperScreen color picker, where supported.
showCopyColorClipboard button.
showSelectDropdown when selectItems is populated.
showCheckboxCheckbox when checkboxLabel is set.
  • ewColorPickerPanel (boolean, default true): Alternate switch for the Panel plugin.
  • ewColorPickerColorMode (boolean or object, default true): Disables ColorMode or merges its options.
  • clearText (string, default '清空'): Clear button label.
  • sureText (string, default '确定'): Confirmation button label.
  • eyedropperText (string, default undefined): Screen sampling button text and accessible label; the fallback label is '取色'.
  • copyColorText (string, default '复制颜色到剪贴板'): Copy button tooltip and accessible label.
  • copiedText (string, default '已复制'): Copy success message displayed for 1.5 seconds.
  • selectItems (SelectOption[], default []): Dropdown choices, each with { label: string, value: string | number, disabled?: boolean }.
  • selectValue (string or number, default undefined): Initial dropdown value.
  • selectPlaceholder (string, default undefined): Placeholder when no option is selected.
  • selectClearable (boolean, default true): Shows a clear button for a selected value.
  • selectTooltip (boolean, default true): Displays the full label when dropdown text is truncated.
  • checkboxLabel (string, default undefined): Checkbox label; an empty label prevents rendering.
  • checkboxChecked (boolean, default false): Initial checked state.
  • checkboxDisabled (boolean, default false): Disables the checkbox.

Gradient options

  • showGradient (boolean, optional): true enables the editor; false hides it. The editor is hidden by default unless gradient or a nonempty gradientStops array is supplied.
  • gradient (string or GradientValue, default undefined): Initial CSS gradient or structured gradient data.
  • gradientType ('linear', 'radial', or 'conic', default 'linear'): Gradient type.
  • gradientRepeating (boolean, default false): Enables repeating gradients.
  • gradientStops (Array<string | GradientStop>): Initial stops; defaults to the current or default color (red if unset) and white.
  • gradientAngle (number, default 180): Linear angle in degrees.
  • gradientInterpolation (string or null, default null): Color interpolation hint, such as oklab or oklch longer hue.
  • minGradientStops (number, default 2): Minimum number of color stops.
  • maxGradientStops (number, default 8): Maximum number of color stops.
  • syncStopsOnChange (boolean, default true): Applies panel color changes to the selected stop.

A GradientStop has color: string and optional percentage positions position and position2. The second position creates a constant-color segment. GradientValue contains the following fields:

FieldType or default
typelinear, radial, or conic; default linear.
repeatingBoolean; default false.
angle{ value: number, unit: 'deg' | 'rad' | 'grad' | 'turn' }; default 180deg.
radialShapecircle or ellipse; default ellipse.
radialSizeCSS size string; default farthest-corner.
conicFromSame structure as angle; default 0deg.
position{ x: number, y: number }; defaults to 50%, 50%.
interpolationString or null; default null.
stopsArray of GradientStop objects.

Callback Functions

CallbackArguments and purpose
changeColor(color)Color string whenever setColor() runs, including valid text input and swatch selection.
sure(color, picker)Confirmed color and picker instance.
clear(picker)Picker instance after resetting the selection.
togglePicker(isOpen)Boolean after a panel toggle.
changeMode(mode, picker)hex, rgb, or hsl and the picker instance.
onClick(box)Box plugin after its toggle handler; blocked when disabled or readonly.
onMouseEnter(box)Box plugin on pointer entry.
onMouseLeave(box)Box plugin on pointer exit.
onEyedropperPick(color)Screen-sampled sRGB hex string.
onCopyColor(color)Color string after a successful clipboard copy.
onSelectChange(value, option)Selected value and option object.
onSelectClear()Dropdown selection cleared.
onCheckboxChange(checked)New boolean checked state.
gradientChange(css, value)Serialized CSS gradient string and structured gradient data.

API Methods

MethodDescription
ewColorPicker.use(Plugin)Registers a plugin class; returns the constructor for chaining and ignores duplicate registrations.
mount(el?)Creates the mount points and applies plugins; returns the instance.
getContainer()Returns the host HTMLElement.
getMountPoint(name)Returns the root or panelContainer HTMLElement, or undefined if unavailable.
showPanel(animationType?, duration?)Opens the panel; initializes an empty selection from the default color or red.
hidePanel(animationType?, duration?)Closes the panel; accepts an optional animation and duration in milliseconds.
openPicker()Alias for showPanel().
closePicker()Alias for hidePanel().
setColor(color)Sets the color string, updates HSVA for nonempty colors, and emits change. Pass '' to clear the string value.
getColor()Returns the current color string.
getHsvaColor()Returns a copy of { h, s, v, a }.
setHsvaColor(hsva)Sets HSVA state silently; use setColor() to update the UI and notify listeners.
getOptions()Returns the live merged options object.
updateOptions(newOptions)Merges options, reapplies the merged defaultColor if valid, refreshes plugins, and emits options-update.
syncAllPlugins(color)Calls the color synchronization hook on plugins that implement it.
on(type, fn, context?)Registers a listener and returns the instance.
once(type, fn, context?)Registers a one-time listener and returns the instance.
off(type?, fn?)Removes a listener, all listeners for an event, or every listener when called with no arguments.
trigger(type, ...args)Runs event listeners with the supplied arguments.
emit(type, ...args)Dispatches listeners and invokes matching clear, sure, or togglePicker callbacks. Manual clear/sure dispatch does not supply the usual button callback arguments.
use(plugin)Calls the instance plugin’s install(this) hook if present; returns the picker.
destroy()Removes picker DOM, plugins, and outside-click handling; emits destroy. Repeated calls are safe.
getDestroyedStatus()Returns a boolean indicating whether the instance is destroyed.

To resize the picker and retain its selected color, pass the current color as defaultColor when updating the options. This also makes it the reset color for Clear.

picker.updateOptions({
  panelMode: 'small',
  defaultColor: picker.getColor()
});

Instance properties

PropertyMeaning
optionsMerged options.
wrapperRoot picker HTMLElement.
pluginsMap of plugin instances by plugin name.
currentColorCurrent color string; update via setColor().
hsvaColorHSVA state.
currentModeCore mode field (Hex, RGB, or HSV); use the ColorMode plugin for the input mode.
pickerFlagPanel open state.
panelWidth, panelHeightPanel dimensions.
panelLeft, panelTopPanel position.

Events

EventPayload and timing
change(color); synchronous color change.
sure(color, picker); confirmed selection.
clear(); Clear button action.
toggle(isOpen); panel toggle after the animation.
options-update(options); configuration update after refreshing plugins.
mode-change(mode); new hex, rgb, or hsl input mode.
destroy(); instance teardown.
const logMode = mode => console.log('Mode:', mode);
picker.on('mode-change', logMode);
picker.once('sure', color => console.log('First confirmed color:', color));
// Remove a particular listener
picker.off('mode-change', logMode);

Plugin API

Access a registered plugin through picker.plugins[pluginName].

PackagePlugin name
boxewColorPickerBox
panelewColorPickerPanel
hueewColorPickerHue
alphaewColorPickerAlpha
inputewColorPickerInput
input-numberewColorPickerInputNumber
selectewColorPickerSelect
checkboxewColorPickerCheckbox
buttonewColorPickerButton
predefineewColorPickerPredefine
color-modeewColorPickerColorMode
eyedropperewColorPickerEyedropper
copy-colorewColorPickerCopyColor
gradientewColorPickerGradient
utilsewColorPickerConsole (version banner; omit when importing plugins on demand).

Trigger, panel, sliders, and input

The color input accepts 3-, 6-, and 8-digit hex values, RGB/RGBA, HSL/HSLA, and an empty string.

Plugin method or propertyDescription
Box: enableBox(enable = true)Show or hide the trigger.
Box: update(keys?)Refresh selected option keys.
Box: updateChildren()Refresh the swatch icon.
Box: setBoxSize()Reapply trigger dimensions.
Box: setBoxBgColor(color?), clearBoxBgColor()Set or reset the swatch background.
Box: setBoxState(), setDisabled(disabled)Sync state classes or toggle disabled state.
Box: bindMouseEvents(onEnter?, onLeave?), unbindHandler()Attach hover handlers or remove DOM event bindings.
Box: destroy()Remove the trigger.
Panel: render()Rebuild panel DOM.
Panel: updateCursorPosition(s, v)Set cursor position using saturation and value from 0 to 100.
Panel: updateColor(s, v)Apply saturation/value to the color.
Panel: updateHueBg(hue?)Update the base hue.
Panel: calculateContainerSize(), handleAutoPosition()Measure or reposition the panel.
Panel: calculatePosition(position, align, boxW, boxH)Returns { left, top } for the placement.
Panel: adjustForViewport(root, left, top)Returns corrected { left, top } coordinates.
Panel: destroy()Remove the panel.
Hue: enableHue(enable = true), hasHueShow/hide the slider; hasHue is a boolean getter/setter.
Hue: updateHue(hue)Apply hue (0 to 360 degrees).
Hue: updateHueThumbPosition(hue)Move the thumb only.
Hue: hueBar, hueThumb, isHorizontalDOM references and orientation flag.
Alpha: enableAlpha(enable = true), hasAlphaShow/hide the opacity slider; hasAlpha is a boolean getter/setter.
Alpha: updateAlpha(alpha)Apply opacity (0 to 1).
Alpha: updateAlphaThumbPosition(alpha)Move the thumb only.
Alpha: alphaBar, alphaThumb, isHorizontalDOM references and orientation flag.
Input: enableInput(enable = true), hasInputShow/hide the field; hasInput is a boolean getter/setter.
Input: setValue(value), getValue()Set or retrieve the text value; setting it alone does not change the picker color.
Input: setDisabled(disabled)Toggle field availability.
Input: update(color)Format and display a color string.
Input: onInputColor(value)Apply valid color input with a 300ms debounce.
Input: inputText input element or null.

Buttons, swatches, and color modes

Plugin method or propertyDescription
Button: enableClear(enable = true), enableSure(enable = true), enableButtons(enable = true)Toggle Clear, Sure, or both controls.
Button: hasClear, hasSureBoolean getters/setters for action buttons.
Button: setClearText(text), setSureText(text)Change button labels.
Button: setDisabled(disabled), updateOptions()Toggle disabled state or refresh controls.
Button: onClearColor(), onSureColor()Execute the Clear or Sure action (100ms debounce).
Button: clearButton, sureButtonButton elements or null.
Predefine: updatePredefineColors(colors)Replace the swatch list.
Predefine: setDisabled(index, disabled)Change availability of one swatch.
Predefine: onPredefineColorClick(event, color)Apply a swatch color (100ms debounce).
Predefine: predefineItems, containerSwatch DOM nodes and their container.
ColorMode: getCurrentMode(), currentModeRead the current lowercase hex, rgb, or hsl mode.
ColorMode: setMode(mode)Switch input mode (100ms debounce).
ColorMode: switchToNextMode(), switchToPreviousMode()Cycle through modes in either direction.
ColorMode: onModeChange(mode)Handle a mode change.
ColorMode: updateOptions(), updateInputStructure()Refresh settings or rebuild input controls.
ColorMode: updateInputValues(color)Synchronize channel values.
ColorMode: updateColorFromRgbInputs(), updateColorFromHslInputs()Recompose the color from the channel inputs.
ColorMode: restoreDefaultInput()Restore the regular text field.
Eyedropper: run(), updateOptions(), destroy()Render if supported, refresh, or remove the screen sampler.
Eyedropper: container, buttonDOM references or null.
CopyColor: run(), updateOptions(), destroy()Render, refresh, or remove the clipboard control.
CopyColor: container, button, tipDOM references or null.
Console: handleOptions(), run(), install(core)Merge options (currently a no-op), print the banner once, or install manually.

Gradient methods

Access these methods through picker.plugins.ewColorPickerGradient. Drag a stop to change its position or click the preview bar to insert a stop at the interpolated color.

MethodDescription
getGradient()Returns a CSS gradient string.
getGradientValue()Returns a structured copy of the gradient.
getStops()Returns a copy of the stop array.
setGradient(value)Accepts CSS or a partial GradientValue and refreshes the editor.
setStops(stops)Replaces color stops.
addStop(color, position?)Inserts a stop; returns its index or -1 if full.
removeStop(index?)Removes the given or selected stop; returns a boolean.
updateOptions()Refreshes the editor from the picker options.
destroy()Removes the editor and event bindings.

Import these helpers from @ew-color-picker/gradient to work with gradients as data. Use percentages for stop positions. Interpolation supports sRGB, linear sRGB, HSL, OKLab, and OKLCH (including its hue directions); LAB, LCH, and HWB hints use sRGB interpolation.

FunctionDescription
parseGradient(css)Parses linear, radial, conic, and repeating CSS gradients into a GradientValue; returns null for invalid input. Accepts deg, rad, grad, turn, to directions, interpolation hints, radial/conic positions, and double-position stops.
serializeGradient(value)Converts a GradientValue into a CSS string.
interpolateStops(stops, position, interpolation?)Returns the interpolated color at a percentage position.
resolveGradientPositions(stops)Returns an array of resolved numeric stop positions.

Additional panel controls

When adding a Select or Checkbox through the picker, load select.css and tooltip.css or checkbox.css, respectively, from @ew-color-picker/style/dist/.

Plugin methodDescription
InputNumber: createInputNumber(options)Creates an InputNumber component.
InputNumber: run(), updateOptions(), destroy()Create the default control, refresh disabled state, or destroy managed inputs.
Select: createSelect(options)Creates a Select component.
Select: run(), updateOptions(), destroy()Render when choices exist, refresh, or remove the dropdown.
Checkbox: createCheckbox(options)Creates a Checkbox component.
Checkbox: run(), updateOptions(), destroy()Render when a label is set, refresh, or remove the checkbox.

InputNumber options: value (number, 0), min (number, -Infinity), max (number, Infinity), step (number, 1), precision (number, 0), disabled (boolean, false), placeholder (string, ''), size (small, default, or large; default), prefix (string, 'ew-'), onChange(value), onBlur(value), and onFocus(event). onChange is debounced by 300ms.

Select options: value (string or number, undefined), items (SelectOption[], []), placeholder (string, ''), disabled (boolean, false), size (small, default, or large; default), prefix (string, 'ew-'), clearable (boolean, true), tooltip (boolean, true; shows truncated labels in a tooltip), onChange(value, option), onClear(), onOpen(), and onClose().

Checkbox options: checked (boolean, false), label (string, ''), disabled (boolean, false), size (small, default, or large; default), prefix (string, 'ew-'), and onChange(checked).

Component methodDescription
InputNumber: getValue(), setValue(value, triggerChange = true)Read or set the clamped numeric value; false suppresses onChange.
Select: getValue(), setValue(value, triggerChange?)Read or set the selection; false skips the change callback.
Select: clear(triggerChange?)Reset selection; false skips onClear.
Select: setItems(items)Replace choices.
Select: open(), close(), isDropdownOpen()Control or inspect dropdown visibility.
Checkbox: isChecked(), setChecked(checked, triggerChange?)Read or set checked state; false skips onChange.
Checkbox: setLabel(label)Change checkbox label.
All three: setDisabled(disabled)Toggle disabled state.
All three: getElement()Return the root DOM element.
All three: destroy()Remove the component and its listeners.

Standalone Input and Button

The aggregate package also exports Input and Button for use outside the picker. Import the corresponding input.css or button.css from @ew-color-picker/style/dist/. Each component accepts an options object and exposes getElement() for mounting its DOM node and destroy() for cleanup.

Input optionType and default
value, placeholderStrings; both ''.
sizesmall, default, or large; default.
typetext, password, number, or search; text.
disabled, readonlyBooleans; both false.
prefixClass prefix; 'ew-'.
onChange(value, event?)Called on input or programmatic value change.
onFocus(value, event?), onBlur(value, event?)Focus and blur callbacks.
onEnter(value, event?)Enter key callback.
Input methodDescription
getValue(), setValue(value, triggerChange = true)Read or set the string; false skips onChange.
setPlaceholder(text)Change the placeholder.
setDisabled(disabled), setReadonly(readonly)Change input state.
focus()Focus the input.
getElement()Returns the input element.
destroy()Removes the input and its event handlers.
Button optionType and default
textString; ''.
typedefault, primary, danger, or text; default.
sizesmall, default, or large; default.
disabled, blockBooleans; both false. block makes the button full-width.
nativeTypebutton, submit, or reset; button.
prefixClass prefix; 'ew-'.
onClick(event)Mouse click callback.
Button methodDescription
setText(text)Change the label.
setDisabled(disabled), isDisabled()Change or read disabled state.
setType(type)Change the button style.
getElement()Returns the button element.
destroy()Removes the button and its event handler.

Tooltip

Import Tooltip from the aggregate package or the default export from @ew-color-picker/tooltip. Load @ew-color-picker/style/dist/tooltip.css. The isTextTruncated(el) helper from the tooltip package checks whether a label is truncated.

Tooltip optionType, default, and purpose
targetElement or selector; optional trigger.
contentString or HTMLElement; optional content.
rawContentBoolean, false; parses strings as HTML when enabled. Sanitize untrusted content first.
prefixString, 'ew-'; class prefix.
effectdark or light; dark.
placementSame 12 placement names as panelPlacement; bottom.
fallbackPlacementsArray of placement names, []; defaults to trying the opposite side.
visibleOptional boolean; controls visibility through setOptions().
disabledBoolean, false; disables triggers and show requests.
offset, arrowOffsetNumbers, 12 and 5 (px); anchor gap and minimum arrow edge distance.
showArrowBoolean, true; displays the arrow.
showAfter, hideAfter, autoCloseNumbers, 0, 200, 0 (ms); show delay, hide delay, and automatic closing. Zero disables automatic closing.
popperClass, popperStyleString class and string or object style; both ''.
appendToElement or selector, document.body; tooltip parent.
teleported, enterableBooleans, both true; mount in the specified parent and permit pointer entry.
triggerhover, click, focus, contextmenu, or an array of these; hover.
virtualTriggering, virtualRefBoolean, false, and element or object exposing getBoundingClientRect(), null; use a virtual anchor.
triggerKeysString array, ['Enter', 'Space']; keyboard triggers for click mode.
persistentBoolean, true; retain hidden DOM.
transitionString, ''; custom transition class.
ariaLabelString, ''; accessible label.
focusOnTargetBoolean, false; returns focus to the trigger after hiding.
popperOptionsObject, { strategy: 'fixed' }; accepts fixed or absolute positioning.
className, containerLegacy aliases for popperClass and appendTo; container accepts an HTMLElement.
Tooltip event / option callbackPayload and timing
beforeShow / onBeforeShowOptional event before showing.
show / onShowOptional event after showing.
beforeHide / onBeforeHideOptional event before hiding.
hide / onHideOptional event after hiding.
visibleChange / onVisibleChangeBoolean visibility change or request.
Tooltip methodDescription
show(content?, anchor?), hide()Request showing or hiding; empty content hides the hint.
onOpen(), onClose()Request opening or closing.
isVisible(), isFocusInsideContent()Check visibility or focus inside the tooltip.
getElement(), getContentElement(), getTrigger()Retrieve the tooltip, its content, or its trigger.
updatePopper()Recalculate position and arrow.
setContent(content), setOptions(options)Replace content or merge options.
on(event, handler), off(event, handler?)Add or remove event listeners.
destroy()Remove DOM, timers, and event handlers.

Styling and Customization

Style a picker through its generated classes. To theme one instance, scope your CSS to its host or, when using appendTo, its relocated panel container.

#color-picker .ew-color-picker-box {
  border-radius: 10px;
}
.ew-color-picker-sure-btn {
  background: #16856b;
  color: white;
  border-color: #16856b;
}

The panel sets these CSS custom properties inline. Use panelMode for preset sizes.

CSS variablePurpose
--panel-widthPanel width; the large preset uses 285px, 302px, or 320px depending on slider orientation.
--panel-heightPanel height; the large preset uses 180px.

CSS classes

For the first table, prepend .ew-color-picker- to each suffix unless a full class name is shown.

Class suffixElement or state
.ew-color-picker (full class)Root wrapper; data-uid identifies the instance.
panel-container, panel-container-hiddenPopup container and hidden state.
bottom-row, extra-rowBottom controls and toolbar.
box, box-arrow-icon, box-close-iconTrigger and its two color-state icons.
.is-disabled, .is-readonly (full classes)Trigger states.
panel, panel-dynamic-sizeSaturation/value area and dynamic sizing marker.
white-panel, black-panel, panel-cursorGradient layers and cursor.
slider, is-horizontal, is-verticalHue slider and orientation.
slider-bar, slider-thumbHue track and thumb.
.ew-alpha (full class)Alpha slider modifier.
alpha-slider-wrapper, alpha-slider-bg, alpha-slider-bar, alpha-slider-thumbOpacity controls.
input-container, input-container-flex, input, input-defaultColor text field and wrappers.
.ew-input-disabled (full class)Disabled input state.
drop-btn-group, drop-btn-group-multi, drop-btn-group-singleButton group and layout modifiers.
clear-btn, sure-btn, drop-btnAction buttons and shared style.
eyedropper-group, eyedropper-btn, eyedropper-text, iconScreen sampling controls and icon.
copy-group, copy-btn, copy-tipCopy control and success message.
mode-container, mode-up-btn, mode-down-btn, mode-textInput mode switcher.
inputs-group, inputs-col, input-labelNumeric color channels.
predefine-container, predefine-color, predefine-color-item, predefine-color-disabled, predefine-color-activePreset swatches and states.
ClassElement or state
.ew-input-numberNumeric component root.
.ew-input-number--small, .ew-input-number--default, .ew-input-number--largeNumeric input sizes.
.ew-input-number--focused, .ew-input-number--disabledNumeric input states.
.ew-input-number__input, .ew-input-number__buttons, .ew-input-number__button, .ew-input-number__button--up, .ew-input-number__button--downInput and steppers.
.ew-select, .ew-select--small, .ew-select--default, .ew-select--largeDropdown root and sizes.
.ew-select--open, .ew-select--disabledDropdown states.
.ew-select__trigger, .ew-select__value, .ew-select__value--placeholderTrigger and selected value.
.ew-select__clear, .ew-select__clear--hidden, .ew-select__clear-icon, .ew-select__arrow, .ew-select__arrow-iconDropdown controls.
.ew-select__dropdown, .ew-select__option, .ew-select__option--selected, .ew-select__option--active, .ew-select__option--disabledOption list and states; data-select-index identifies the option index.
.ew-checkbox, .ew-checkbox--default, .ew-checkbox--checkedCheckbox root and states.
.ew-checkbox__input, .ew-checkbox__box, .ew-checkbox__check-icon, .ew-checkbox__labelCheckbox elements.
.ew-gradient-container, .ew-gradient-preview, .ew-gradient-preview-barGradient editor and preview.
.ew-gradient-handle, .ew-gradient-handle-activeStop handles and active state.
.ew-gradient-row, .ew-gradient-row-type, .ew-gradient-row-radial, .ew-gradient-row-position, .ew-gradient-row-interp, .ew-gradient-row-stopGradient control rows.
.ew-tooltip, .ew-tooltip--dark, .ew-tooltip--light, .ew-tooltip--visible, .ew-tooltip--enterable, .ew-tooltip__content, .ew-tooltip__arrowTooltip structure, theme, and states; data-placement indicates placement on the tooltip and arrow.

Custom CSS prefix

The distributed CSS uses ew-. When compiling your own SCSS, configure $prefix on every stylesheet your picker uses and pass the same value to the constructor.

@use '@ew-color-picker/style/src/index.scss' with ($prefix: 'brand-');
@use '@ew-color-picker/style/src/input-number.scss' with ($prefix: 'brand-');
const picker = new ewColorPicker({ el: '#color-picker', prefix: 'brand-' });

Write a Custom Plugin

Register a class with a unique static pluginName before creating the picker. Render into root or panelContainer, and use the instance event API to track changes.

import ewColorPicker from '@ew-color-picker/ew-color-picker';
class ColorLabel {
  static pluginName = 'colorLabel';
  constructor(picker) {
    this.picker = picker;
    this.label = document.createElement('output');
    picker.getMountPoint('root').append(this.label);
    this.handleChange = color => {
      this.label.textContent = color;
    };
    this.handleChange(picker.getColor());
    picker.on('change', this.handleChange);
  }
  destroy() {
    this.picker.off('change', this.handleChange);
    this.label.remove();
  }
}
ewColorPicker.use(ColorLabel);
const picker = new ewColorPicker({ el: '#color-picker', defaultColor: '#16856b' });
Plugin memberPurpose
static pluginNameRequired unique registration key.
static applyOrderOptional ApplyOrder.Pre (-1), unset (0), or ApplyOrder.Post (1), imported from @ew-color-picker/utils; equal priorities follow registration order.
constructor(core)Receives the picker instance for rendering and subscriptions.
destroy()Optional cleanup hook.
install(core)Optional manual installation hook.
updateOptions()Optional configuration refresh hook.
syncColor(color)Optional synchronization hook called by syncAllPlugins().
CustomOptionsCore TypeScript extension point for declaring custom plugin options.

Static ewColorPicker.plugins contains registration entries (name, applyOrder, ctor); ewColorPicker.pluginsMap maps plugin names to registration flags.

Alternatives

You Might Be Interested In:


Leave a Reply