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;
}

1 thought on “Random hex color Generator JavaScript”

  1. Pingback: setTimeout random interval in javascript

Leave a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.