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

Color Picker 2.4.4

Color Picker is a simple JavaScript application 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 application 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 application core.

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

Get the color as raw, hex string

Features

Usage

Browser

<!DOCTYPE html>
<html dir="ltr">
  <head>
    <meta charset="utf-8">
    <link href="./index.min.css" rel="stylesheet">
  </head>
  <body>
    <p>
      <input type="text">
    </p>
    <script src="./index.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>

Node.js

Functions and methods in this application are mostly native JavaScript and are intended for use by the browser. Node.js doesn’t know about the DOM, so this kind of practice will probably be used more often to build new browser packages than to be used directly in the Node.js server.

CommonJS

const CP = require('@taufik-nurrohman/color-picker').default;

const picker = new CP(document.querySelector('input'));

picker.on('change', function (r, g, b, a) {
    this.source.value = this.color(r, g, b, a);
});

ECMAScript

import CP from '@taufik-nurrohman/color-picker';

const picker = new CP(document.querySelector('input'));

picker.on('change', function (r, g, b, a) {
    this.source.value = this.color(r, g, b, a);
});

Examples

Settings

let picker = new CP(source, color = 'HEX');
let picker = new CP(source, state = {
        color: 'HEX'
    });
Name Description
source The source element that holds the initial color data.
color Name of the color parser defined in the CP object.
state The configuration data.
state.color Name of the color parser defined in the CP object.

Methods and Properties

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

Hex color converter as the default color string parser. This is the only color mode that this application 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.instances

Return the color picker instances.

for (let key in CP.instances) {
    console.log(key);
    console.log(CP.instances[key]);
}

CP.state

This property stores the initial values of picker.state.

let picker = new CP(source, {
        foo: ['bar', 'baz', 'qux']
    });

console.log([CP.state, picker.state]);

CP.version

Return the color picker version.

let version = CP.version,
    major = version.split('.')[0];

if (+major < 2) {
    // Has no alpha channel support
}

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.current

Return the active color picker control panel element.

picker.on('change', function (r, g, b, a) {
    if (this.current.classList.contains('color-picker:h')) {
        // Is dragging the hue control
    }
});

picker.enter(to)

Show the color picker panel.

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

picker.exit()

Hide the color picker panel.

picker.exit();

picker.fit([x, y])

Set color picker position measured from the window edges.

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

picker.get()

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

console.log(picker.get());

picker.pop()

Remove custom color picker features from the source element.

picker.self

Return the color picker element.

picker.self.style.borderWidth = '4px';

picker.set(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.set(255, 255, 0, .5);

picker.source

Return the color picker source element that holds the initial color value.

picker.source.addEventListener('click', function () {
    console.log(this.nodeName);
}, false);

picker.state

Return the modified color picker states.

picker.visible

Check if color picker panel is visible.

if (picker.visible) { … }

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 you put '#ffff00' to the method argument, it will come out as [255, 255, 0, 1] and if you 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 = 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];
    }
    // Return 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 application so that the application can detect RGB color input through the string representation of RGB color given to the input element, set the color state value to 'RGB':

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

Hooks

Name Description
blur Adding a blur hook will disable the default blur behavior, that is, to hide the color picker panel.
change Will be triggered on every color change.
drag Will be triggered when the color picker control is dragging.
enter Will be triggered when color picker panel is visible.
exit Will be triggered when color picker panel is hidden.
fit Will be triggered when color picker panel is positioned.
focus Adding a focus hook will disable the default focus behavior, that is, to show the color picker panel.
pop Will be triggered after picker.pop().
start Will be triggered when the color picker control starts dragging.
stop Will be triggered when the color picker control stops dragging.

picker.fire(event, data)

Trigger a hook.

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

picker.hooks

Return the added hooks.

console.log(picker.hooks);

picker.off(event, then)

Remove a hook.

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

picker.on(event, then)

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

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! ❤️