JSFiddle - React, Tailwind, and code Playground
by ckissi
HTML
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/@simonwep/[email protected]/dist/pickr.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/[email protected]/dist/themes/classic.min.css">
<div class="flex justify-center space-x-4 mt-10">
<div id="box1" class="rounded-lg p-5 w-1/4 bg-blue-500">
<svg class="w-6 h-6 mb-2" fill="currentColor" viewBox="0 0 20 20">
<path d="M2 10a8 8 0 1116 0 8 8 0 01-16 0zm8-4a4 4 0 100 8 4 4 0 000-8z"/>
</svg>
<p>Sample text 1</p>
<div class="pickr" id="pickr1"></div>
</div>
<div id="box2" class="rounded-lg p-5 w-1/4 bg-red-500">
<svg class="w-6 h-6 mb-2" fill="currentColor" viewBox="0 0 20 20">
<path d="M2 10a8 8 0 1116 0 8 8 0 01-16 0zm8-4a4 4 0 100 8 4 4 0 000-8z"/>
</svg>
<p>Sample text 2</p>
<div class="pickr" id="pickr2"></div>
</div>
<div id="box3" class="rounded-lg p-5 w-1/4 bg-green-500">
<svg class="w-6 h-6 mb-2" fill="currentColor" viewBox="0 0 20 20">
<path d="M2 10a8 8 0 1116 0 8 8 0 01-16 0zm8-4a4 4 0 100 8 4 4 0 000-8z"/>
</svg>
<p>Sample text 3</p>
<div class="pickr" id="pickr3"></div>
</div>
</div>
JavaScript
function createPickr(elementId, boxId) {
const pickr = Pickr.create({
el: elementId,
theme: 'classic',
components: {
preview: true,
opacity: true,
hue: true,
interaction: {
hex: true,
rgba: true,
input: true,
save: true
}
}
});
pickr.on('save', (color, instance) => {
pickr.hide();
const hexColor = color.toHEXA().toString();
const pastelColor = getPastelColor(hexColor);
document.getElementById(boxId).style.backgroundColor = pastelColor;
});
}
function getPastelColor(hexColor) {
const rgb = hexToRgb(hexColor);
const pastelRgb = rgb.map(value => Math.floor((value + 255) / 2));
return rgbToHex(pastelRgb);
}
function hexToRgb(hex) {
let r = 0, g = 0, b = 0;
if (hex.length == 4) {
r = parseInt(hex[1] + hex[1], 16);
g = parseInt(hex[2] + hex[2], 16);
b = parseInt(hex[3] + hex[3], 16);
} else if (hex.length == 7) {
r = parseInt(hex[1] + hex[2], 16);
g = parseInt(hex[3] + hex[4], 16);
b = parseInt(hex[5] + hex[6], 16);
}
return [r, g, b];
}
function rgbToHex(rgb) {
const [r, g, b] = rgb;
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
}
document.addEventListener('DOMContentLoaded', () => {
createPickr('#pickr1', 'box1');
createPickr('#pickr2', 'box2');
createPickr('#pickr3', 'box3');
pastelColor = getPastelColor('#3c82f6');
...