DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Color Palette Generator with JavaScript

A colour palette generator creates five colours that work together — the kind of tool every designer opens before starting a project. It is a great beginner project because it teaches colour maths, the Clipboard API, and keyboard interaction, and the result is genuinely useful.

Colours are easiest to generate in HSL: pick a random hue, then derive the other colours by rotating around the colour wheel. Complementary colours sit opposite each other, analogous colours sit next to each other, and triadic colours sit 120 degrees apart:

function randomHSL(hue, saturation, lightness) {
  return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}

function generatePalette() {
  const baseHue = Math.floor(Math.random() * 360);
  const schemes = {
    analogous: [0, 30, 60, 90, 120],
    complementary: [0, 180, 30, 210, 60],
    triadic: [0, 120, 240, 60, 180],
  };
  const offsets = schemes[currentScheme];
  return offsets.map((offset) => {
    const hue = (baseHue + offset) % 360;
    const lightness = 30 + Math.floor(Math.random() * 40);
    return { hsl: randomHSL(hue, 70, lightness), hex: hslToHex(hue, 70, lightness) };
  });
}
Enter fullscreen mode Exit fullscreen mode

Hex values are what designers actually copy, so convert each HSL colour to hex. The conversion is standard maths — no library needed:

function hslToHex(h, s, l) {
  s /= 100; l /= 100;
  const k = (n) => (n + h / 30) % 12;
  const a = s * Math.min(l, 1 - l);
  const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  const toHex = (x) => Math.round(x * 255).toString(16).padStart(2, "0");
  return `#${toHex(f(0))}${toHex(f(8))}${toHex(f(4))}`.toUpperCase();
}
Enter fullscreen mode Exit fullscreen mode

Clicking a colour copies its hex code, and pressing the spacebar generates a new palette — the two interactions that make the tool feel professional. Locking a colour you like keeps it while the rest regenerate, which is how the real palette tools work:

let locked = [false, false, false, false, false];

document.getElementById("palette").addEventListener("click", async (e) => {
  const swatch = e.target.closest(".swatch");
  if (!swatch) return;
  const hex = swatch.dataset.hex;
  await navigator.clipboard.writeText(hex);
  swatch.querySelector(".hex").textContent = "Copied!";
  setTimeout(() => (swatch.querySelector(".hex").textContent = hex), 1200);
});

document.addEventListener("keydown", (e) => {
  if (e.code === "Space" && document.activeElement.tagName !== "INPUT") {
    e.preventDefault();
    renderPalette();
  }
});

document.querySelectorAll(".lock").forEach((btn, i) => {
  btn.addEventListener("click", (e) => {
    e.stopPropagation();
    locked[i] = !locked[i];
    btn.textContent = locked[i] ? "Locked" : "Lock";
  });
});
Enter fullscreen mode Exit fullscreen mode

Rendering is straightforward: five swatches, each with its colour as the background and its hex code as the label. Dark text on light colours and light text on dark colours keeps the labels readable — check the lightness value and pick the text colour from it.

Colour choices decide whether a design sells or gets ignored, and the psychology behind that is well documented — the best marketing books for beginners in India explain how brands use colour to signal trust, urgency, and luxury, which is exactly the thinking that turns a random palette into a deliberate one.

Ways to extend it: add a scheme picker (analogous, complementary, triadic, monochrome), add a "copy whole palette" button that copies all five hex codes at once, add an export-to-CSS-variables button, or let the user paste an image and extract its dominant colours with a canvas. The HSL maths here is the same foundation behind theme generators, chart libraries, and design systems.

Top comments (0)