A colour picker is a small app designers and developers open every day: pick a colour, copy its code, build a palette. Building one teaches you input events, the clipboard, and a little colour math — and you end up with a tool you will actually use.
What you are building
A colour input, a big preview of the chosen colour, its HEX, RGB, and HSL values, a copy button for each format, a random-colour button, and a palette of five colours that work together.
The core is one input
HTML already has a colour picker built in. The app is mostly about displaying what it returns:
<input type="color" id="picker" value="#10b981">
<div id="preview"></div>
<p>HEX: <span id="hex">#10b981</span> <button data-copy="hex">Copy</button></p>
<p>RGB: <span id="rgb"></span> <button data-copy="rgb">Copy</button></p>
<p>HSL: <span id="hsl"></span> <button data-copy="hsl">Copy</button></p>
<button id="random">Random Colour</button>
function hexToRgb(hex) {
const n = parseInt(hex.slice(1), 16);
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };
}
function updateColour(hex) {
const { r, g, b } = hexToRgb(hex);
document.getElementById("preview").style.background = hex;
document.getElementById("hex").textContent = hex;
document.getElementById("rgb").textContent = `rgb(${r}, ${g}, ${b})`;
}
document.getElementById("picker").addEventListener("input", (event) => {
updateColour(event.target.value);
});
Copying and random colours
document.querySelectorAll("[data-copy]").forEach((button) => {
button.addEventListener("click", async () => {
const target = document.getElementById(button.dataset.copy);
await navigator.clipboard.writeText(target.textContent);
button.textContent = "Copied!";
setTimeout(() => (button.textContent = "Copy"), 1200);
});
});
document.getElementById("random").addEventListener("click", () => {
const hex = "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0");
document.getElementById("picker").value = hex;
updateColour(hex);
});
padStart(6, "0") matters: without it, a random value like 0x00ff11 can come out as a 5-character hex code, which is not a valid colour.
Generating a palette
A simple trick for a five-colour palette: take the base colour, convert it to HSL, and shift the hue by a fixed step for each swatch. Analogous palettes shift by 20–30 degrees; complementary palettes add 180. Showing the contrast ratio of the colour against white and black text is a genuinely useful extra — it tells the user whether the colour works as a background.
What to add next
Add saved colours in localStorage, a palette export as CSS variables, or a gradient generator that blends two picked colours. Each one builds on the same conversion helpers.
Top comments (0)