
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.bodyto 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 event | Description |
|---|---|
modelValue | Optional color string; bound through v-model. |
options | Core picker options, default {}; the wrapper supplies el. |
update:modelValue, change | Current color string. |
sure | Confirmed color string. |
clear, destroy | No arguments. |
toggle | Boolean panel state. |
mode-change | Input mode string. |
| React prop | Description |
|---|---|
value | Optional controlled color string. |
options | Core 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, style | Host 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
| Signature | Description |
|---|---|
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(stringorHTMLElement): Mount target; the fallback container isdocument.body.defaultColor(string, default''): Initial color and reset value for the Clear button.disabled(boolean, defaultfalse): Disables picker controls.readonly(boolean, defaultfalse): Prevents the trigger swatch from opening or closing the picker.size(string,number, or{ width, height }, default'normal'): Trigger size; presetsmini,small,normal,medium, andlargecorrespond 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 torgbwhen the Alpha plugin is present; otherwisehex.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(stringorRecord<string, string>, default''): Inline styles for the trigger swatch.prefix(string, default'ew-'): Generated CSS class prefix; match the compiled stylesheet prefix.
panelMode | Panel dimensions (width x height) |
|---|---|
mini | 180 x 140px; 202px wide with both sliders horizontal. |
small | 220 x 150px; 247px wide with both sliders horizontal. |
medium | 250 x 165px; 281px wide with both sliders horizontal. |
large | 285 x 180px; 320px wide with both sliders horizontal. |
Panel behavior
isClickOutside(boolean, defaulttrue): Closes the panel when clicking outside it.autoPanelPosition(boolean, defaultfalse): Automatically positions the panel relative to the Box trigger. For a custom trigger, useappendTowithpanelPlacement.panelPlacement(string, default'bottom'): Acceptstop-start,top,top-end,left-start,left,left-end,right-start,right,right-end,bottom-start,bottom, andbottom-end.appendTo(stringorHTMLElement, defaultundefined): 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, ornull, defaultnull): Constrains automatic placement to the visible bounds of a container;nulluses the viewport.togglePickerAnimation(string, default'default'): Choosedefaultfor instant toggling,heightfor sliding, oropacityfor fading.pickerAnimationTime(number, default200): Animation duration in milliseconds, capped at 10000.
Controls and labels
| Option | Control |
|---|---|
hasBox | Trigger swatch. |
hasPanel | Saturation/value panel. |
hasInput | Text color field. |
hasClear | Clear button. |
hasSure | Confirmation button. |
hue | Hue slider. |
alpha | Opacity slider. |
showButton | Both action buttons. |
showColorMode | HEX/RGB/HSL switcher. |
showInputNumber | InputNumber plugin’s own input; ColorMode channel inputs are unaffected. |
showEyedropper | Screen color picker, where supported. |
showCopyColor | Clipboard button. |
showSelect | Dropdown when selectItems is populated. |
showCheckbox | Checkbox when checkboxLabel is set. |
ewColorPickerPanel(boolean, defaulttrue): Alternate switch for the Panel plugin.ewColorPickerColorMode(booleanorobject, defaulttrue): Disables ColorMode or merges its options.clearText(string, default'清空'): Clear button label.sureText(string, default'确定'): Confirmation button label.eyedropperText(string, defaultundefined): 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(stringornumber, defaultundefined): Initial dropdown value.selectPlaceholder(string, defaultundefined): Placeholder when no option is selected.selectClearable(boolean, defaulttrue): Shows a clear button for a selected value.selectTooltip(boolean, defaulttrue): Displays the full label when dropdown text is truncated.checkboxLabel(string, defaultundefined): Checkbox label; an empty label prevents rendering.checkboxChecked(boolean, defaultfalse): Initial checked state.checkboxDisabled(boolean, defaultfalse): Disables the checkbox.
Gradient options
showGradient(boolean, optional):trueenables the editor;falsehides it. The editor is hidden by default unlessgradientor a nonemptygradientStopsarray is supplied.gradient(stringorGradientValue, defaultundefined): Initial CSS gradient or structured gradient data.gradientType('linear','radial', or'conic', default'linear'): Gradient type.gradientRepeating(boolean, defaultfalse): Enables repeating gradients.gradientStops(Array<string | GradientStop>): Initial stops; defaults to the current or default color (red if unset) and white.gradientAngle(number, default180): Linear angle in degrees.gradientInterpolation(stringornull, defaultnull): Color interpolation hint, such asoklaboroklch longer hue.minGradientStops(number, default2): Minimum number of color stops.maxGradientStops(number, default8): Maximum number of color stops.syncStopsOnChange(boolean, defaulttrue): 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:
| Field | Type or default |
|---|---|
type | linear, radial, or conic; default linear. |
repeating | Boolean; default false. |
angle | { value: number, unit: 'deg' | 'rad' | 'grad' | 'turn' }; default 180deg. |
radialShape | circle or ellipse; default ellipse. |
radialSize | CSS size string; default farthest-corner. |
conicFrom | Same structure as angle; default 0deg. |
position | { x: number, y: number }; defaults to 50%, 50%. |
interpolation | String or null; default null. |
stops | Array of GradientStop objects. |
Callback Functions
| Callback | Arguments 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
| Method | Description |
|---|---|
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
| Property | Meaning |
|---|---|
options | Merged options. |
wrapper | Root picker HTMLElement. |
plugins | Map of plugin instances by plugin name. |
currentColor | Current color string; update via setColor(). |
hsvaColor | HSVA state. |
currentMode | Core mode field (Hex, RGB, or HSV); use the ColorMode plugin for the input mode. |
pickerFlag | Panel open state. |
panelWidth, panelHeight | Panel dimensions. |
panelLeft, panelTop | Panel position. |
Events
| Event | Payload 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].
| Package | Plugin name |
|---|---|
box | ewColorPickerBox |
panel | ewColorPickerPanel |
hue | ewColorPickerHue |
alpha | ewColorPickerAlpha |
input | ewColorPickerInput |
input-number | ewColorPickerInputNumber |
select | ewColorPickerSelect |
checkbox | ewColorPickerCheckbox |
button | ewColorPickerButton |
predefine | ewColorPickerPredefine |
color-mode | ewColorPickerColorMode |
eyedropper | ewColorPickerEyedropper |
copy-color | ewColorPickerCopyColor |
gradient | ewColorPickerGradient |
utils | ewColorPickerConsole (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 property | Description |
|---|---|
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), hasHue | Show/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, isHorizontal | DOM references and orientation flag. |
Alpha: enableAlpha(enable = true), hasAlpha | Show/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, isHorizontal | DOM references and orientation flag. |
Input: enableInput(enable = true), hasInput | Show/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: input | Text input element or null. |
Buttons, swatches, and color modes
| Plugin method or property | Description |
|---|---|
Button: enableClear(enable = true), enableSure(enable = true), enableButtons(enable = true) | Toggle Clear, Sure, or both controls. |
Button: hasClear, hasSure | Boolean 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, sureButton | Button 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, container | Swatch DOM nodes and their container. |
ColorMode: getCurrentMode(), currentMode | Read 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, button | DOM references or null. |
CopyColor: run(), updateOptions(), destroy() | Render, refresh, or remove the clipboard control. |
CopyColor: container, button, tip | DOM 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.
| Method | Description |
|---|---|
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.
| Function | Description |
|---|---|
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 method | Description |
|---|---|
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 method | Description |
|---|---|
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 option | Type and default |
|---|---|
value, placeholder | Strings; both ''. |
size | small, default, or large; default. |
type | text, password, number, or search; text. |
disabled, readonly | Booleans; both false. |
prefix | Class 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 method | Description |
|---|---|
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 option | Type and default |
|---|---|
text | String; ''. |
type | default, primary, danger, or text; default. |
size | small, default, or large; default. |
disabled, block | Booleans; both false. block makes the button full-width. |
nativeType | button, submit, or reset; button. |
prefix | Class prefix; 'ew-'. |
onClick(event) | Mouse click callback. |
| Button method | Description |
|---|---|
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 option | Type, default, and purpose |
|---|---|
target | Element or selector; optional trigger. |
content | String or HTMLElement; optional content. |
rawContent | Boolean, false; parses strings as HTML when enabled. Sanitize untrusted content first. |
prefix | String, 'ew-'; class prefix. |
effect | dark or light; dark. |
placement | Same 12 placement names as panelPlacement; bottom. |
fallbackPlacements | Array of placement names, []; defaults to trying the opposite side. |
visible | Optional boolean; controls visibility through setOptions(). |
disabled | Boolean, false; disables triggers and show requests. |
offset, arrowOffset | Numbers, 12 and 5 (px); anchor gap and minimum arrow edge distance. |
showArrow | Boolean, true; displays the arrow. |
showAfter, hideAfter, autoClose | Numbers, 0, 200, 0 (ms); show delay, hide delay, and automatic closing. Zero disables automatic closing. |
popperClass, popperStyle | String class and string or object style; both ''. |
appendTo | Element or selector, document.body; tooltip parent. |
teleported, enterable | Booleans, both true; mount in the specified parent and permit pointer entry. |
trigger | hover, click, focus, contextmenu, or an array of these; hover. |
virtualTriggering, virtualRef | Boolean, false, and element or object exposing getBoundingClientRect(), null; use a virtual anchor. |
triggerKeys | String array, ['Enter', 'Space']; keyboard triggers for click mode. |
persistent | Boolean, true; retain hidden DOM. |
transition | String, ''; custom transition class. |
ariaLabel | String, ''; accessible label. |
focusOnTarget | Boolean, false; returns focus to the trigger after hiding. |
popperOptions | Object, { strategy: 'fixed' }; accepts fixed or absolute positioning. |
className, container | Legacy aliases for popperClass and appendTo; container accepts an HTMLElement. |
| Tooltip event / option callback | Payload and timing |
|---|---|
beforeShow / onBeforeShow | Optional event before showing. |
show / onShow | Optional event after showing. |
beforeHide / onBeforeHide | Optional event before hiding. |
hide / onHide | Optional event after hiding. |
visibleChange / onVisibleChange | Boolean visibility change or request. |
| Tooltip method | Description |
|---|---|
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 variable | Purpose |
|---|---|
--panel-width | Panel width; the large preset uses 285px, 302px, or 320px depending on slider orientation. |
--panel-height | Panel 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 suffix | Element or state |
|---|---|
.ew-color-picker (full class) | Root wrapper; data-uid identifies the instance. |
panel-container, panel-container-hidden | Popup container and hidden state. |
bottom-row, extra-row | Bottom controls and toolbar. |
box, box-arrow-icon, box-close-icon | Trigger and its two color-state icons. |
.is-disabled, .is-readonly (full classes) | Trigger states. |
panel, panel-dynamic-size | Saturation/value area and dynamic sizing marker. |
white-panel, black-panel, panel-cursor | Gradient layers and cursor. |
slider, is-horizontal, is-vertical | Hue slider and orientation. |
slider-bar, slider-thumb | Hue track and thumb. |
.ew-alpha (full class) | Alpha slider modifier. |
alpha-slider-wrapper, alpha-slider-bg, alpha-slider-bar, alpha-slider-thumb | Opacity controls. |
input-container, input-container-flex, input, input-default | Color text field and wrappers. |
.ew-input-disabled (full class) | Disabled input state. |
drop-btn-group, drop-btn-group-multi, drop-btn-group-single | Button group and layout modifiers. |
clear-btn, sure-btn, drop-btn | Action buttons and shared style. |
eyedropper-group, eyedropper-btn, eyedropper-text, icon | Screen sampling controls and icon. |
copy-group, copy-btn, copy-tip | Copy control and success message. |
mode-container, mode-up-btn, mode-down-btn, mode-text | Input mode switcher. |
inputs-group, inputs-col, input-label | Numeric color channels. |
predefine-container, predefine-color, predefine-color-item, predefine-color-disabled, predefine-color-active | Preset swatches and states. |
| Class | Element or state |
|---|---|
.ew-input-number | Numeric component root. |
.ew-input-number--small, .ew-input-number--default, .ew-input-number--large | Numeric input sizes. |
.ew-input-number--focused, .ew-input-number--disabled | Numeric input states. |
.ew-input-number__input, .ew-input-number__buttons, .ew-input-number__button, .ew-input-number__button--up, .ew-input-number__button--down | Input and steppers. |
.ew-select, .ew-select--small, .ew-select--default, .ew-select--large | Dropdown root and sizes. |
.ew-select--open, .ew-select--disabled | Dropdown states. |
.ew-select__trigger, .ew-select__value, .ew-select__value--placeholder | Trigger and selected value. |
.ew-select__clear, .ew-select__clear--hidden, .ew-select__clear-icon, .ew-select__arrow, .ew-select__arrow-icon | Dropdown controls. |
.ew-select__dropdown, .ew-select__option, .ew-select__option--selected, .ew-select__option--active, .ew-select__option--disabled | Option list and states; data-select-index identifies the option index. |
.ew-checkbox, .ew-checkbox--default, .ew-checkbox--checked | Checkbox root and states. |
.ew-checkbox__input, .ew-checkbox__box, .ew-checkbox__check-icon, .ew-checkbox__label | Checkbox elements. |
.ew-gradient-container, .ew-gradient-preview, .ew-gradient-preview-bar | Gradient editor and preview. |
.ew-gradient-handle, .ew-gradient-handle-active | Stop 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-stop | Gradient control rows. |
.ew-tooltip, .ew-tooltip--dark, .ew-tooltip--light, .ew-tooltip--visible, .ew-tooltip--enterable, .ew-tooltip__content, .ew-tooltip__arrow | Tooltip 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 member | Purpose |
|---|---|
static pluginName | Required unique registration key. |
static applyOrder | Optional 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(). |
CustomOptions | Core 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
- Feature-rich Color & Gradient Picker In JavaScript – xncolorpicker
- Modern Feature-Rich Color Picker in Vanilla JavaScript – jscolorpicker
- Lightweight & Fast Color Picker Web Component – color-dialog-box







