Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Beginner ⏱ 30 min

🎨 Build a Colour Palette Generator with JavaScript

🎯 What You'll Build

A tool that generates random 5-colour palettes, lets you lock colours you like, and copies hex codes to the clipboard.

📋 What You'll Need

1

HTML layout

Five colour panels side by side.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Palette Generator</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

<?php require_once __DIR__ . '/../promo_banner.php'; ?>

  <header>
    <h1>🎨 Palette Generator</h1>
    <button id="generate">Generate (Space)</button>
  </header>
  <div class="palette" id="palette"></div>
  <script src="palette.js"></script>
</body>
</html>
2

JavaScript logic

Random hex generation, lock toggle, and clipboard copy.

function randomHex() {
  return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');
}

function textColour(hex) {
  const r = parseInt(hex.slice(1,3),16), g = parseInt(hex.slice(3,5),16), b = parseInt(hex.slice(5,7),16);
  return (0.299*r + 0.587*g + 0.114*b) > 160 ? '#000' : '#fff';
}

let palette = Array(5).fill(null).map(() => ({ hex: randomHex(), locked: false }));

function render() {
  document.getElementById('palette').innerHTML = palette.map((c, i) => `
    <div class="swatch" style="background:${c.hex};color:${textColour(c.hex)}" data-i="${i}">
      <button class="lock ${c.locked ? 'locked' : ''}" onclick="lock(${i})">${c.locked ? '🔒' : '🔓'}</button>
      <span class="hex" onclick="copy('${c.hex}')">${c.hex}</span>
      <span class="copy-hint">click to copy</span>
    </div>`).join('');
}

function generate() {
  palette = palette.map(c => c.locked ? c : { hex: randomHex(), locked: false });
  render();
}

function lock(i) { palette[i].locked = !palette[i].locked; render(); }

function copy(hex) {
  navigator.clipboard.writeText(hex);
  alert(`Copied ${hex}`);
}

document.getElementById('generate').addEventListener('click', generate);
document.addEventListener('keydown', e => { if (e.code === 'Space' && e.target === document.body) { e.preventDefault(); generate(); } });
render();
💡 Tip: Export the palette as a CSS :root block of custom properties — one button that copies `--color-1: #abc123;` etc.

🎉 You Did It!

Your palette generator works like a mini Coolors. Add colour harmony modes (complementary, triadic) for a portfolio standout project.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.