JavaScript Random Color Generator Functions – Hex, RGB, HSL and More
Colors play a vital role in web design, UI development, and creative coding. Whether you're building a dynamic theme generator, a random color picker, or experimenting with color effects, JavaScript provides various ways to generate random colors. In this guide, we explore different methods to create random colors, including Hex, RGB, HSL, and hue-based variations.
Contents
JavaScript Random Hex Color Generate Function
Hexadecimal color codes are commonly used in web development. This method generates a random 6-digit hex color code (e.g., #ff5733
).
Demo:
const randomHexColor = () => {
return '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
};
Usage with HTML example:
<button onclick="create_random_hex()">Random Color</button>
<div id="preview-hex-color"></div>
<script>
const create_random_hex = () => {
let preview = document.getElementById('preview-hex-color');
let color = randomHexColor();
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
A hue-based color generator allows you to create colors with random hues while keeping saturation and lightness values controlled. This ensures vibrant and visually appealing results.
Demo:
const generateRandomHueColor = () => {
const hue = Math.floor(Math.random() * 361); // Random hue (0-360)
const saturation = 100;
const lightness = 50;
const hueToRgb = (primary, secondary, tempHue) => {
if (tempHue < 0) tempHue += 1;
if (tempHue > 1) tempHue -= 1;
if (tempHue < 1 / 6) return primary + (secondary - primary) * 6 * tempHue;
if (tempHue < 1 / 2) return secondary;
if (tempHue < 2 / 3) return primary + (secondary - primary) * (2 / 3 - tempHue) * 6;
return primary;
};
const secondaryComponent = lightness < 50
? lightness * (1 + saturation / 100)
: lightness + saturation / 100 - lightness * saturation / 100;
const primaryComponent = 2 * lightness / 100 - secondaryComponent;
const red = hueToRgb(primaryComponent, secondaryComponent, hue / 360 + 1 / 3);
const green = hueToRgb(primaryComponent, secondaryComponent, hue / 360);
const blue = hueToRgb(primaryComponent, secondaryComponent, hue / 360 - 1 / 3);
const toHext = value => value.toString(16).padStart(2, '0');
return `#${toHext(Math.round(red * 255))}${toHext(Math.round(green * 255))}${toHext(Math.round(blue * 255))}`;
};
// Example usage
// console.log(generateRandomHueColor()); // Example output: #ff8000
Usage with HTML example:
<button onclick="get_random_hue_color()">Random Hue Color</button>
<div id="preview-hue-color"></div>
<script>
const get_random_hue_color = () => {
let preview = document.getElementById('preview-hue-color');
let color = generateRandomHueColor();
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
This function generates colors with a fixed hue but random lightness and darkness levels, allowing you to create dynamic themes with light and dark variations.
Demo:
const randomHueColorWithLightness = (saturation, lightness) => {
// Ensure saturation and lightness values stay within the valid range
// saturation 20 - 100;
// lightness 20 - 85;
const hue = Math.floor(Math.random() * 361);
const adjustedSaturation = Math.max(0, Math.min(100, saturation));
const adjustedLightness = Math.max(0, Math.min(100, lightness));
const normalizedHue = hue / 360;
const normalizedSaturation = adjustedSaturation / 100;
const normalizedLightness = adjustedLightness / 100;
let red, green, blue;
if (normalizedSaturation === 0) {
// If saturation is 0, the color is a shade of gray
red = green = blue = normalizedLightness;
} else {
const hueToRgb = (primary, secondary, tempHue) => {
if (tempHue < 0) tempHue += 1;
if (tempHue > 1) tempHue -= 1;
if (tempHue < 1 / 6) return primary + (secondary - primary) * 6 * tempHue;
if (tempHue < 1 / 2) return secondary;
if (tempHue < 2 / 3) return primary + (secondary - primary) * (2 / 3 - tempHue) * 6;
return primary;
};
const secondaryComponent = normalizedLightness < 0.5 ?
normalizedLightness * (1 + normalizedSaturation) :
normalizedLightness + normalizedSaturation - normalizedLightness * normalizedSaturation;
const primaryComponent = 2 * normalizedLightness - secondaryComponent;
red = hueToRgb(primaryComponent, secondaryComponent, normalizedHue + 1 / 3);
green = hueToRgb(primaryComponent, secondaryComponent, normalizedHue);
blue = hueToRgb(primaryComponent, secondaryComponent, normalizedHue - 1 / 3);
}
const toHex = value => Math.round(value * 255).toString(16).padStart(2, '0');
return `#${toHex(red)}${toHex(green)}${toHex(blue)}`;
};
Usage with HTML example:
<button onclick="get_random_hue_light_dark_color()">Random Hue light and dark Color</button>
<div id="preview-hue-light-dark-color"></div>
<script>
const get_random_hue_light_dark_color = () => {
let preview = document.getElementById('preview-hue-light-dark-color');
const saturation = 50;
const lightness = 40;
let color = randomHueColorWithLightness(saturation, lightness);
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
If you need colors that are closely related but still have some variation in brightness, this function generates similar shades by slightly adjusting lightness and saturation.
Demo:
const generateSimilarLightDarkColor = (hexColor) => {
// Normalize HEX color by removing "#" and expanding shorthand HEX
hexColor = hexColor.replace(/^#/, '');
if (hexColor.length === 3) {
hexColor = hexColor.split('').map(hex => hex + hex).join('');
}
// Extract RGB values
const match = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexColor);
if (!match) return null;
let red = parseInt(match[1], 16) / 255;
let green = parseInt(match[2], 16) / 255;
let blue = parseInt(match[3], 16) / 255;
// Convert RGB to Hue (HSL Conversion)
const maxColor = Math.max(red, green, blue);
const minColor = Math.min(red, green, blue);
let hue;
if (maxColor === minColor) {
hue = 0;
} else {
const delta = maxColor - minColor;
switch (maxColor) {
case red:
hue = (green - blue) / delta + (green < blue ? 6 : 0);
break;
case green:
hue = (blue - red) / delta + 2;
break;
case blue:
hue = (red - green) / delta + 4;
break;
}
hue = Math.round(hue * 60); // Convert to degrees
}
// Generate random Saturation (20-100) and Lightness (20-80)
const saturation = Math.floor(Math.random() * (100 - 20)) + 20;
const lightness = Math.floor(Math.random() * (80 - 20)) + 20;
// Convert HSL back to RGB
const convertHueToRgb = (primary, secondary, tempHue) => {
if (tempHue < 0) tempHue += 1;
if (tempHue > 1) tempHue -= 1;
if (tempHue < 1 / 6) return primary + (secondary - primary) * 6 * tempHue;
if (tempHue < 1 / 2) return secondary;
if (tempHue < 2 / 3) return primary + (secondary - primary) * (2 / 3 - tempHue) * 6;
return primary;
};
const normalizedHue = hue / 360;
const normalizedSaturation = saturation / 100;
const normalizedLightness = lightness / 100;
const secondaryComponent = normalizedLightness < 0.5
? normalizedLightness * (1 + normalizedSaturation)
: normalizedLightness + normalizedSaturation - normalizedLightness * normalizedSaturation;
const primaryComponent = 2 * normalizedLightness - secondaryComponent;
red = convertHueToRgb(primaryComponent, secondaryComponent, normalizedHue + 1 / 3);
green = convertHueToRgb(primaryComponent, secondaryComponent, normalizedHue);
blue = convertHueToRgb(primaryComponent, secondaryComponent, normalizedHue - 1 / 3);
// Convert RGB to HEX
const convertToHex = value => Math.round(value * 255).toString(16).padStart(2, '0');
return `#${convertToHex(red)}${convertToHex(green)}${convertToHex(blue)}`;
};
// Example usage
// console.log(generateSimilarLightDarkColor("#3498db")); // Example output: #6f9bea
Usage with HTML example:
<button onclick="get_similar_color()">Random Similar Color</button>
<div id="preview-hue-light-dark-color"></div>
<script>
const get_similar_color = () => {
let preview = document.getElementById('preview-hue-light-dark-color');
const hueHexColor = "#f00"; // red
let color = generateSimilarLightDarkColor(hueHexColor);
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
RGB (Red, Green, Blue) color values range from 0-255
. This method produces colors using three random values, offering full control over opacity and blending.
Demo:
const generateRandomRgb = (useCommas = true) => {
const randomRgbValues = Array.from({ length: 3 }, () => Math.floor(Math.random() * 256));
const separator = useCommas ? ', ' : ' ';
return `rgb(${randomRgbValues.join(separator)})`;
};
// Example usage
// console.log(generateRandomRgb()); // Output: rgb(123, 45, 67)
// console.log(generateRandomRgb(false)); // Output: rgb(123 45 67)
Usage with HTML example:
<button onclick="get_random_rgb()">Random RGB Color</button>
<div id="preview-rgb-color"></div>
<script>
const get_random_rgb = () => {
let preview = document.getElementById('preview-rgb-color');
let color = generateRandomRgb();
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
HSL (Hue, Saturation, Lightness) provides a more intuitive way to generate colors. By adjusting the H, S, and L values randomly, you can create vibrant or muted color palettes as needed.
Demo:
const generateRandomHsl = (useDegrees = false) => {
const hue = Math.floor(Math.random() * 361);
const saturation = Math.floor(Math.random() * 101);
const lightness = Math.floor(Math.random() * 101);
return useDegrees
? `hsl(${hue}deg ${saturation}% ${lightness}%)`
: `hsl(${hue}, ${saturation}%, ${lightness}%)`;
};
// Example usage
// console.log(generateRandomHsl()); // Output: hsl(263, 11%, 90%)
// console.log(generateRandomHsl(true)); // Output: hsl(263deg 11% 90%)
Usage with HTML example:
<button onclick="get_random_hsl()">Random HSL Color</button>
<div id="preview-hsl-color"></div>
<script>
const get_random_hsl = () => {
let preview = document.getElementById('preview-hsl-color');
let color = generateRandomHsl();
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
Warm and cool colors evoke different emotions warm colors (red, orange, yellow) create energy, while cool colors (blue, green) feel calming. This function randomly generates a warm or cool HSL color based on the chosen category.
Demo:
const generateRandomWarmCool = (warm = true) => {
const hue = warm
? Math.floor(Math.random() * 90) // Covers Red (0°) to Yellow (90°)
: Math.floor(Math.random() * 120) + 180; // Covers Cyan (180°) to Blue (300°)
const saturation = Math.random() * 40 + 60; // Ensures decent saturation (60% - 100%)
const lightness = Math.random() * 30 + 40; // Keeps lightness moderate (40% - 70%)
return `hsl(${hue}, ${saturation.toFixed(1)}%, ${lightness.toFixed(1)}%)`;
};
Usage:
<button onclick="get_random_warm()">Random warm color</button>
<div id="preview-warm-color"></div>
<script>
const get_random_warm = () => {
let preview = document.getElementById('preview-warm-color');
let color = generateRandomWarmCool(); // warm
//let color = generateRandomWarmCool(false); // cool
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
Grayscale colors range from pure black to pure white, with various shades of gray in between. This function randomly picks a grayscale color by setting the RGB values equally.
Demo:
const generateRandomGrayscale = () => {
const gray = Math.floor(Math.random() * 256);
return `rgb(${gray}, ${gray}, ${gray})`;
};
Usage:
<button onclick="get_grayscale()">Random grayscale color</button>
<div id="preview-grayscale-color"></div>
<script>
const get_grayscale = () => {
let preview = document.getElementById('preview-grayscale-color');
let color = generateRandomGrayscale();
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
Neon colors are bright, vibrant, and eye-catching. This function generates a random neon color by ensuring high RGB values, making the color appear vivid and glowing.
Demo:
const generateRandomNeon = () => {
const channel = () => Math.floor(Math.random() * 128) + 128;
return `rgb(${channel()}, ${channel()}, ${channel()})`;
};
Usage:
<button onclick="get_neon()">Random Neon Color</button>
<div id="preview-neon-color"></div>
<script>
const get_neon = () => {
let preview = document.getElementById('preview-neon-color');
let color = generateRandomNeon();
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>
Pastel colors are soft, light, and soothing, commonly used in artistic and modern design. This function creates a pastel color by keeping RGB values high, ensuring a soft appearance.
Demo:
const generateRandomPastel = () => {
const channel = () => Math.floor(Math.random() * 100) + 156; // Keeps colors light (156-255)
return `rgb(${channel()}, ${channel()}, ${channel()})`;
};
Usage:
<button onclick="get_pastel()">Random pastel color</button>
<div id="preview-pastel-color"></div>
<script>
const get_pastel = () => {
let preview = document.getElementById('preview-pastel-color');
let color = generateRandomPastel();
let div = '<div style="background-color:'+color+';">'+color+'</div>';
preview.innerHTML = div;
};
</script>