JSFiddle - React, Tailwind, and code Playground
by paulL
HTML
<input type="color-picker" value=""/>
JavaScript
var COLORPICKER = {
mouse_inside: false,
to_hex: function (dec) {
hex = dec.toString(16);
return hex.length == 2 ? hex : '0' + hex;
},
show: function () {
var input = $(this);
var position = input.offset();
COLORPICKER.$colors = $('<canvas width="230" height="150" ></canvas>');
COLORPICKER.$colors.css({
'position': 'absolute',
'top': position.top + input.height() + 9,
'left': position.left,
'cursor': 'crosshair',
'display': 'none'
});
$('body').append(COLORPICKER.$colors.fadeIn());
COLORPICKER.colorctx = COLORPICKER.$colors[0].getContext('2d');
COLORPICKER.render();
COLORPICKER.$colors
.click(function (e) {
var new_color = COLORPICKER.get_color(e);
$(input).css({'background-color': new_color}).val(new_color).trigger('change').removeClass('color-picker-binded');
COLORPICKER.close();
})
.hover(function () {
COLORPICKER.mouse_inside=true;
}, function () {
COLORPICKER.mouse_inside=false;
});
$("body").mouseup(function () {
if (!COLORPICKER.mouse_is_inside) COLORPICKER.close();
});
},
bind_inputs: function () {
$('input[type="color-picker"]').not('.color-picker-binded').each(function () {
$(this).click(COLORPICKER.show);
}).addClass('color-picker-binded');
},
close: function () {COLORPICKER.$colors.fadeOut(COLORPICKER.$colors.remove);},
get_color: function (e) {
var pos_x = e.pageX - COLORPICKER.$colors.offset().left;
var pos_y = e.pageY - COLORPICKER.$colors.offset().top;
data = COLORPICKER.colorctx.getImageData(pos_x, pos_y, 1, 1).data;
return '#' + COLORPICKER.to_hex(data[0]) + COLORPICKER.to_hex(data[1]) + COLORPICKER.to_hex(data[2]);
},
//...