Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript to generate random hex codes of color
Generating random hex color codes in JavaScript involves creating a 6-character string from hexadecimal digits (0-9, A-F) and prefixing it with '#'. This is useful for creating dynamic color schemes, themes, or visual effects.
Understanding Hex Color Codes
Hex color codes use the format #RRGGBB where each pair represents red, green, and blue values in hexadecimal (0-F). For example, #FF0000 is pure red, #00FF00 is green, and #0000FF is blue.
Method 1: Using Math.random() with Character Selection
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Hex Color Generator</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
.color-display {
width: 200px;
height: 200px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
margin: 20px 0;
font-size: 18px;
font-weight: bold;
color: white;
text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}
.generate-btn {
padding: 10px 20px;
font-size: 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Random Hex Color Generator</h1>
<button class="generate-btn">Generate Random Color</button>
<div class="color-display" id="colorDisplay">Click Generate</div>
<script>
function generateRandomHex() {
const hexChars = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += hexChars[Math.floor(Math.random() * 16)];
}
return color;
}
document.querySelector('.generate-btn').addEventListener('click', () => {
const randomColor = generateRandomHex();
const display = document.getElementById('colorDisplay');
display.style.backgroundColor = randomColor;
display.textContent = randomColor;
});
</script>
</body>
</html>
Method 2: Using toString(16) Method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hex Generator - Method 2</title>
<style>
.color-box {
width: 150px;
height: 150px;
margin: 10px;
display: inline-block;
text-align: center;
line-height: 150px;
color: white;
font-weight: bold;
border-radius: 8px;
}
</style>
</head>
<body>
<h2>Generate Multiple Random Colors</h2>
<button onclick="generateMultipleColors()">Generate 5 Colors</button>
<div id="colorContainer"></div>
<script>
function generateHexUsingToString() {
// Generate random number between 0 and 16777215 (0xFFFFFF)
const randomNum = Math.floor(Math.random() * 16777215);
// Convert to hex and pad with zeros if needed
return "#" + randomNum.toString(16).padStart(6, '0');
}
function generateMultipleColors() {
const container = document.getElementById('colorContainer');
container.innerHTML = '';
for (let i = 0; i < 5; i++) {
const color = generateHexUsingToString();
const colorBox = document.createElement('div');
colorBox.className = 'color-box';
colorBox.style.backgroundColor = color;
colorBox.textContent = color;
container.appendChild(colorBox);
}
}
</script>
</body>
</html>
Method 3: Functional Approach with Validation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Advanced Hex Generator</title>
<style>
.color-info {
margin: 20px 0;
padding: 20px;
border-radius: 10px;
color: white;
text-align: center;
}
.controls {
margin: 20px 0;
}
button {
margin: 5px;
padding: 8px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
background-color: #28a745;
color: white;
}
</style>
</head>
<body>
<h2>Advanced Hex Color Generator</h2>
<div class="controls">
<button onclick="generateAndDisplay()">Generate Color</button>
<button onclick="generatePalette()">Generate Palette</button>
</div>
<div id="output"></div>
<script>
const generateHexColor = () => {
const hex = () => Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
return `#${hex()}${hex()}${hex()}`;
};
const isValidHex = (color) => {
return /^#[0-9A-F]{6}$/i.test(color);
};
function generateAndDisplay() {
const color = generateHexColor();
const output = document.getElementById('output');
if (isValidHex(color)) {
output.innerHTML = `
<div class="color-info" style="background-color: ${color}">
<h3>Generated Color: ${color}</h3>
<p>RGB equivalent: ${hexToRgb(color)}</p>
</div>
`;
}
}
function generatePalette() {
const colors = Array.from({length: 4}, () => generateHexColor());
const output = document.getElementById('output');
output.innerHTML = colors.map(color =>
`<div class="color-info" style="background-color: ${color}; display: inline-block; width: 23%; margin: 1%;">
${color}
</div>`
).join('');
}
function hexToRgb(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `rgb(${r}, ${g}, ${b})`;
}
</script>
</body>
</html>
Comparison of Methods
| Method | Performance | Readability | Flexibility |
|---|---|---|---|
| Character Selection | Good | High | Easy to modify |
| toString(16) | Best | Medium | Compact code |
| Functional Approach | Good | High | Most flexible |
Common Use Cases
Random hex colors are commonly used for:
- Dynamic UI themes and color schemes
- Data visualization with unique colors
- Background generation for user profiles
- Color palette generators for design tools
Conclusion
JavaScript provides multiple approaches to generate random hex colors. The character selection method offers clarity, while toString(16) provides efficiency. Choose based on your specific needs for performance and code maintainability.
Advertisements
