EN
JavaScript - generate random hex color
3 points
In this article, we would like to show you how to generate random hex colors using JavaScript.
Quick solution:
xxxxxxxxxx
1
function randomColor() {
2
var result = '';
3
for (var i = 0; i < 6; ++i) {
4
var value = Math.floor(16 * Math.random());
5
result += value.toString(16);
6
}
7
return '#' + result;
8
}
In this example, you can see generated color code in hex with preview.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<pre id="color-code"></pre>
5
<div id="color-preview" style="width:100px; height:100px"></div>
6
<script>
7
8
function randomColor() {
9
var result = '';
10
for (var i = 0; i < 6; ++i) {
11
var value = Math.floor(16 * Math.random());
12
result += value.toString(16);
13
}
14
return '#' + result;
15
}
16
17
18
// Usage example:
19
20
var colorCode = document.querySelector('#color-code');
21
var colorPreview = document.querySelector('#color-preview');
22
23
var color = randomColor();
24
25
colorCode.innerText = color; // sets color code (in hex)
26
colorPreview.style.background = color; // sets color preview
27
28
</script>
29
</body>
30
</html>
1. The below solution uses predefined digits that compose hex color.
xxxxxxxxxx
1
const DIGITS = '0123456789ABCDEF';
2
3
function randomColor() {
4
var result = '';
5
for (var i = 0; i < 6; ++i) {
6
var index = Math.floor(16 * Math.random());
7
result += DIGITS[index];
8
}
9
return '#' + result;
10
}
2. One random number solution
xxxxxxxxxx
1
function randomColor() {
2
var dec = Math.floor(0x1000000 * Math.random()); // 0x1000000 = 0xFFFFFF + 1
3
var hex = dec.toString(16);
4
for (var i = hex.length; i < 6; ++i) {
5
hex = '0' + hex;
6
}
7
return '#' + hex;
8
}