How to create a color picker with picker.js

Color pickers are everywhere on the Web today, we see them in a lot in forms and in customization tools.

Even though it’s possible to create this with HTML, JavaScript is a better solution because it provides greater support. Today, we’ll use picker.js to create a simple color picker that you can use in your applications.

The first step towards creating this simple interface is to have our HTML ready, in this case I simply created a button and a span in which we will present the color to the user:

<button class="click">Click</button>
<span class="color"></span>

After this is done, in order to start coding the actual color picker we will need to import the JavaScript file into our page:

<script src="js/picker.min.js"></script>

Now that we have done so, we can start coding. We’ll start by defining a variable that will find the parent element, basically the element that will hold the picker and then based on that element we will create a new instance of the picker:

Using just this code, we’ve already created a color picker but we still need to make this picker is visible on the page and for that we use:

picker.show();

And now, as soon as the page loads we see the picker attached to that element. But we need to make two small changes, first I want the picker to appear at the bottom of the button and for that we need to change the second line a little:

var picker = new Picker({ parent: button, orientation: 'bottom' });

As you can see all I did was add that parameter to this line and the orientation as been changed, if you need more you can also place x and y positions using those parameters.

The second adjustment I want to make is call the picker only when the user clicks the button. For that we need to wrap the show function in a click event handler:

button.onclick = function() {
picker.show();
};

If you reload your page you can see that now we have control over when and where the picker shows up. Both these are completely customizable using parameters and different event handlers.

Now that we have the picker up and running we will add the color we picked to some elements .

The first thing we are going to do is assign the color the user is choosing as the background of the button, this means that every time the user changes the color, the background will be updated. For this we will use the on_change event that comes with picker.js:

As you can see from this code we got the color and placed the RGBA value of it as the HTML of the span so that the users can copy what they choose, and then we took that color in HEX format and placed it as the text color to add some consistency.