Build a Random Color Generator in JavaScript
A random color generator is a quick, satisfying JavaScript project: one click, a new color. Follow the steps, try the live demo, and copy the full source code, including HEX, RGB and HSL output.
What You Will Build
Every web color is just three numbers for red, green and blue, so generating a random color means picking three random values. This project turns that idea into a small app with a big preview circle and a button that generates a new color on every click.
What the finished generator does
- Generates a valid random color and shows it in a large preview.
- Switches between HEX, RGB and HSL so you can learn all three formats.
- Copies the color value to the clipboard with one click.
- Remembers recent colors and lets you restore any of them.
- Stays readable by choosing light or dark text depending on the color.
You only need a basic understanding of HTML, CSS and JavaScript functions and the DOM.
HTML Structure
The page needs a preview, a format selector, two buttons and a place for the history. The preview is a real button, so it is keyboard accessible and can also generate a color when pressed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Random Color Generator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="color-display" aria-label="Generate a new color">
<span id="color-value">#000000</span>
</button>
<select id="format" aria-label="Color format">
<option value="hex">HEX</option>
<option value="rgb">RGB</option>
<option value="hsl">HSL</option>
</select>
<button id="generate-button">Generate Color</button>
<button id="copy-button">Copy</button>
<p id="status" role="status"></p>
<div id="history"></div>
<script src="script.js"></script>
</body>
</html>Styling with CSS
The preview is a circle with a smooth color transition, so every new color fades in instead of snapping. The page background stays neutral, which keeps the focus on the color itself.
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 24px 16px;
}
#color-display {
display: grid;
place-items: center;
width: 200px;
height: 200px;
margin: 40px auto;
border: 0;
border-radius: 50%;
font: bold 1rem monospace;
cursor: pointer;
transition: background-color .4s;
}
button, select {
padding: 10px 20px;
font-size: 1rem;
margin: 4px;
}
#generate-button {
background: #333;
color: #fff;
border: 0;
cursor: pointer;
}
#history button {
width: 32px;
height: 32px;
padding: 0;
border-radius: 50%;
border: 2px solid #ccc;
}JavaScript Logic
The generator picks a random number for the color, converts it to a HEX string, and derives the RGB and HSL versions from that one value. Keeping a single source of truth means the three formats always describe the same color.
Math.floor(Math.random() * 16777215).toString(16), produces fewer than six digits whenever the number is small, for example #a3f. Browsers read that as a different shorter color, or reject it in other contexts. It also never returns #ffffff. The code below pads to six digits with padStart and uses 0x1000000 as the upper bound so every color is possible.const $ = (id) => document.getElementById(id);
let current = '#3d8bff';
const history = [];
// Random HEX color, always six digits
function randomHex() {
const n = Math.floor(Math.random() * 0x1000000);
return '#' + n.toString(16).padStart(6, '0');
}
function hexToRgb(hex) {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function rgbString(hex) {
return 'rgb(' + hexToRgb(hex).join(', ') + ')';
}
function hslString(hex) {
const [r, g, b] = hexToRgb(hex).map((v) => v / 255);
const max = Math.max(r, g, b), min = Math.min(r, g, b);
const l = (max + min) / 2, d = max - min;
let h = 0, s = 0;
if (d) {
s = d / (1 - Math.abs(2 * l - 1));
h = max === r ? ((g - b) / d) % 6
: max === g ? (b - r) / d + 2
: (r - g) / d + 4;
h = Math.round((h * 60 + 360) % 360);
}
return 'hsl(' + h + ', ' + Math.round(s * 100) + '%, ' + Math.round(l * 100) + '%)';
}
// Light text on dark colors, dark text on light colors
function textColor(hex) {
const [r, g, b] = hexToRgb(hex);
return (r * 299 + g * 587 + b * 114) / 1000 > 150 ? '#111' : '#fff';
}
function show(hex) {
current = hex;
const f = $('format').value;
const label = f === 'rgb' ? rgbString(hex) : f === 'hsl' ? hslString(hex) : hex.toUpperCase();
const box = $('color-display');
box.style.backgroundColor = hex;
box.style.color = textColor(hex);
$('color-value').textContent = label;
}
function generate() {
show(randomHex());
history.unshift(current);
history.length = Math.min(history.length, 8);
renderHistory();
}
function renderHistory() {
$('history').textContent = '';
history.forEach((hex) => {
const b = document.createElement('button');
b.style.backgroundColor = hex;
b.setAttribute('aria-label', 'Use ' + hex);
b.addEventListener('click', () => show(hex));
$('history').appendChild(b);
});
}
$('generate-button').addEventListener('click', generate);
$('color-display').addEventListener('click', generate);
$('format').addEventListener('change', () => show(current));
$('copy-button').addEventListener('click', () => {
navigator.clipboard.writeText($('color-value').textContent)
.then(() => { $('status').textContent = 'Copied!'; });
});
generate();How it works
randomHex() creates the color, show() displays it in the chosen format, and generate() ties them together and records the history. Because every format is derived from the HEX value, you can add a new format later by writing one more small function.
The original version also changed the page background on every click. This version keeps the page neutral and colors only the preview, which is easier on the eyes and keeps the text readable.
Live Demo: Random Color Generator in Action
This demo follows the same logic as the code above. Click the circle or the button for a new color, switch formats, copy the value, or tap a recent color to bring it back.
Ideas to Extend the Project
Once the generator works, these features make good practice:
- Color palettes: generate five colors at once and let users lock the ones they like.
- Contrast checker: calculate the contrast ratio between two colors to test accessibility.
- Saved favorites: store favorite colors in localStorage so they survive a refresh.
- Color picker input: add an
input type="color"so users can start from their own color. - Shareable links: put the current color in the URL hash so you can send it to someone.
Frequently Asked Questions
How do you generate a random color in JavaScript?
Pick a random integer from 0 to 16777215 (0xFFFFFF), convert it to base 16 with toString(16), and pad it to six digits with padStart(6, '0'). Prefix it with # to get a valid HEX color.
What is the difference between HEX, RGB and HSL?
They are different ways to write the same color. HEX and RGB describe the amount of red, green and blue, while HSL describes hue, saturation and lightness, which is often easier to adjust by hand.
Why does Math.random() never give me the same color twice in a row?
It can, but with more than 16 million possible colors a repeat is extremely unlikely. If you need guaranteed uniqueness, compare each new color with the previous one and generate again.
Is this project good for beginners?
Yes. It practices functions, event listeners, the DOM and string formatting in under a hundred lines, and you can see the result immediately.
Keep Building with JavaScript
This random color generator shows how a few lines of JavaScript can produce an interactive, polished tool. You learned how to generate valid HEX colors, convert them to RGB and HSL, keep text readable, and build a small history, all using plain HTML, CSS and JavaScript.
