Random hex color Generator JavaScript

Short and effective script to generate random hex color. We start with a random number to multiply with white color (Hex Code is 0xFFFFFF ), now we have to convert the randomly generated values into the hexadecimal value to display the color.

To convert integer values into hexadecimal I have used .toString( radix ) where:

  • 2 – The number will show as a binary value
  • 8 – The number will show as an octal value
  • 16 – The number will show as a hexadecimal value
var hex = Math.floor( Math.random() * 0xFFFFFF );
var res = document.getElementById('result');
var result = "#" + hex.toString(16);

res.style.backgroundColor = result;
res.innerHTML = result;

HTML Section

<div id="result"></div>
#result{
    width: 100px;
    height: 50px;
    display:block;
    text-align: center;
    line-height: 50px;
}

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.