Do you like this project? Please support my Mecha CMS project too. Thank you!

Color Picker v2.0.0

Color Picker is a simple JavaScript widget that aims to provide custom color picker feature to the web with the most basic appearance and usability.


It’s easy to set-up, has no animation effects, and no color support other than hex color code (you can add your own custom color supports yourself). My purpose in making this widget is to provide a JavaScript color picker solution as simple as possible with the most minimal features without requiring any dependency on JavaScript library such as jQuery. Use the available hooks to make your own improvements without having to touch the widget core.

Set the color to red, green, blue, blue with 50% opacity

Get the color as raw, hex string

Features

Usage

<!DOCTYPE html>
<html dir="ltr">
  <head>
    <meta charset="utf-8">
    <link href="color-picker.min.css" rel="stylesheet">
  </head>
  <body>
    <p><input type="text"></p>
    <script src="color-picker.min.js"></script>
    <script>
    const picker = new CP(document.querySelector('input'));
    picker.on('change', function(r, g, b, a) {
        if (1 === a) {
            this.source.value = 'rgb(' + r + ', ' + g + ', ' + b + ')';
        } else {
            this.source.value = 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')';
        }
    });
    </script>
  </body>
</html>

Examples

Settings

const picker = new CP(source, events);
const picker = new CP(source, state = {
        color: 'HEX',
        events: ['touchstart', 'mousedown'],
        parent: null
    });

Instance

All color picker instances will be stored in CP.__instance__. To iterate the instances is possible with CP.each():

CP.each(function(key) {
    console.log(key);
    console.log(this.source);
});

Methods and Properties

CP.version

Return the color picker version.

CP.HEX(color | [r, g, b, a])

Hex color converter as the default color string parser. This is the only color mode that this widget can parse into a series of RGBA color data. You can add your own color parser later to enhance the existing features.

console.log(CP.HEX('#ff0')); // → `[255, 255, 0, 1]`
console.log(CP.HEX([255, 255, 0, 1])); // → `'#ffff00'`

CP._

Return the color picker prototypes if any.

picker.state

Return the modified color picker states.

picker.source

Return the color picker source element that holds the initial color value. It can be any element with a data-color attribute, any element that has value attribute or any element that has color value in its content.

picker.self

Return the color picker element.

picker.current

Return the active color picker control pane element.

picker.visible

Check if color picker pane is visible.

if (picker.visible) { … }

picker.set(r, g, b, a)

Set color picker’s color state based on the given color data.

// Set color picker’s color state to yellow with 50% opacity
picker.set(255, 255, 0, .5);

picker.get()

Get current color value as a series of RGBA color data.

console.log(picker.get());

picker.value(r, g, b, a)

Set source element value and update the color picker’s color state.

// Set color picker’s source element value to yellow with 50% opacity
picker.value(255, 255, 0, .5);

picker.color(r, g, b, a)

Call current color parser function with a name that is defined in the state.color value.

// Convert RGB to HEX in the output
picker.on('change', function(r, g, b, a) {
    this.source.value = this.color(r, g, b, a);
});

// The code above is equal to this code
picker.on('change', function(r, g, b, a) {
    this.source.value = CP.HEX([r, g, b, a]);
});

picker.enter(to)

Show the color picker pane.

picker.enter(); // Enter to the `<body>` element
picker.enter(document.querySelector('#foo')); // Enter to a specific container

picker.exit()

Hide the color picker pane.

picker.exit();

picker.fit([x, y])

Set color picker position measured from the window edges.

picker.enter();
picker.fit([30, 30]);

picker.pop()

Remove custom color picker features from the source element.

Color Converters

Converters are defined as static methods in the scope of CP. This method accepts two types of input, a color string input and an array of red, green, blue and alpha color data. Every input given to this method will return the opposite version of the input. For example, with the CP.HEX() method, if I put '#ffff00' to the method argument, it will come out as [255, 255, 0, 1] and if I put [255, 255, 0, 1] to the method argument, it will come out as '#ffff00'.

To make a color converter, be sure to check the input types first before doing the parsing:

CP.RGB = function(x) {
    if ('string' === typeof x) {
        // Use regular expression here to extract color data from the string input
        // and output it as an array of red, green, blue and alpha color data
        return [r, g, b, a];
    }
    // Returns the string representation of color if input is an array of color data
    return 'rgba(' + x[0] + ', ' + x[1] + ', ' + x[2] + ', ' + x[3] + ')';
};

console.log(CP.RGB('rgba(255, 255, 0, 1)'));
console.log(CP.RGB([255, 255, 0, 1]));

To apply it to the widget so that the widget can detect RGB color input through the string representation of RGB color given to the input element, set the color state value to 'RGB':

var picker = new CP(document.querySelector('input'), {
        color: 'RGB'
    });

Hooks

Name Description
enter Will be triggered when color picker pane is visible.
exit Will be triggered when color picker pane is hidden.
fit Will be triggered when color picker pane is positioned.
change Will be triggered on every color change.
start Will be triggered when the color picker control starts dragging.
drag Will be triggered when the color picker control is dragging.
stop Will be triggered when the color picker control stops dragging.
pop Will be triggered after picker.pop().

picker.on(name, fn)

Add a new hook.

picker.on('change', function(r, g, b, a) {
    console.log(this.color(r, g, b, a));
});
function onChange(r, g, b, a) {
    console.log(this.color(r, g, b, a));
}

picker.on('change', onChange); // With context

picker.off(name, fn)

Remove a hook.

picker.off('change');
picker.off('change', onChange); // With context

picker.fire(name, lot)

Trigger hooks.

picker.fire('change', [255, 255, 0, .5]);

License

Use it for free, pay if you get paid. So, you’ve just benefited financially after using this project? It’s a good idea to share a little financial support with this open source project too. Your support will motivate me to do any further development, as well as to provide voluntary support to overcome problems related to this project.

Thank you! ❤️