Generate Random Hex Color Code in JavaScript

In this blog post, we learn how to generate random hex colors in javascript. There are too many methods to generate Hex color. I shared one of the easiest methods.

Hexadecimal color values are also supported in all browsers. A hexadecimal color is specified with #RRGGBB.

#code

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

    function randomHexColor() {
        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 = randomHexColor();

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

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

Another method

function randomHexColor() {
    var value = Math.floor(0x1000000 * Math.random());  // 0x1000000 = 0xFFFFFF + 1
    return '#' + value.toString(16);
}

I hope It will helps you.