Languages
[Edit]
EN

JavaScript - generate random hex color

3 points
Created by:
Kenya-Spears
500

In this article, we would like to show you how to generate random hex colors using JavaScript.

Quick solution:

function randomColor() {
    var result  = '';
    for (var i = 0; i < 6; ++i) {
        var value = Math.floor(16 * Math.random());
        result += value.toString(16);
    }
    return '#' + result;
}

 

Practical example

In this example, you can see generated color code in hex with preview.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<body>
  <pre id="color-code"></pre>
  <div id="color-preview" style="width:100px; height:100px"></div>
  <script>

    function randomColor() {
        var result  = '';
        for (var i = 0; i < 6; ++i) {
          	var value = Math.floor(16 * Math.random());
          	result += value.toString(16);
        }
        return '#' + result;
    }

    
    // Usage example:

    var colorCode = document.querySelector('#color-code');
    var colorPreview = document.querySelector('#color-preview');

    var color = randomColor();

    colorCode.innerText = color;        // sets color code (in hex)
	colorPreview.style.background = color; // sets color preview

  </script>
</body>
</html>

Alternative solutions

1. The below solution uses predefined digits that compose hex color.

const DIGITS = '0123456789ABCDEF';

function randomColor() {
    var result  = '';
    for (var i = 0; i < 6; ++i) {
        var index = Math.floor(16 * Math.random());
        result += DIGITS[index];
    }
    return '#' + result;
}

2. One random number solution

function randomColor() {
    var dec = Math.floor(0x1000000 * Math.random());  // 0x1000000 = 0xFFFFFF + 1
    var hex = dec.toString(16);
    for (var i = hex.length; i < 6; ++i) {
        hex = '0' + hex;
    }
    return '#' + hex;
}

References

  1. Math.random() - JavaScript | MDN
  2. Math.floor() - JavaScript | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join