Use 1 native HTML5 input type ‘color’ to pop out a colorpicker when we need it

April 14th, 2014 by Alex Leave a reply »

So let’s say we have several places where we need to have a color picker. Some might use a jQuery Colorpicker, bunch of CSS files, gradient images, and so on. But, let’s imagine all browsers support input type="color".

First things first, we create 1 input which will be our color picker:

<input type="color" id="colorpicker" />

Wow, that was hard.. now we add some simple CSS rules to make it invisible, but still “workable”:

#colorpicker { position: absolute; top: -9999px }

Then, let’s say we have 2 places where we need to input our color, but we need it to look custom:

<div>Color is: <span id="color"></span> </div>
<div><input type="button" value="Pick Color" id="colorpickertoggle" /></div>
 
<div>Color is: <span id="color2"></span> </div>
<div><input type="button" value="Pick Color" id="colorpickertoggle2" /></div>

Now, we add the last part – the actual JS code. We will trigger color picker with a button input, and update the proper elements when we get a new value:

var changeelement = 'color';
document.getElementById('colorpickertoggle').addEventListener('click', function() {
    changeelement = 'color';
    document.getElementById('colorpicker').click();
}, false);
document.getElementById('colorpickertoggle2').addEventListener('click', function() {
    changeelement = 'color2';
    document.getElementById('colorpicker').click();
}, false);
document.getElementById('colorpicker').addEventListener('change', function() {
    document.getElementById(changeelement).innerHTML = this.value;
}, false);

Potentially, we can add any amount of buttons and inputs and variables and .. do whatever we want with the value returned by a color picker.

Working fiddle:
http://jsfiddle.net/CW5J8/


Comments are closed.