vsupalov

Generate a random HTML color

October 29, 2011

This function returns a random HTML color string. It uses theĀ randomRange function to generate the numerical value.

function randomColor() {
  var s = "#";

  for (var i = 0; i < 6; i++) {
    s+= randomRange(0,15).toString(16);
  }

  return s;
}

The value range of HTML colors starts at 0 and ends with (hex)ffffff, which is equal to 16777215 in the decimal system. The following method uses less Math.random() calls:

function randomColor() {
  var s = "#";
  var numberPart = randomRange(0,16777215).toString(16);

  while ((numberPart.length + s.length) < 7) { // insert leading '0's
    s+='0';
  }

  return s+numberPart;
}

Join the mailing list!


Subscribe to get notified about future articles and stay in touch via email.

I write about Django, Kubernetes, Docker, automation- and deployment topics, but would also like to keep you up to date about news around the business-side of things.

Privacy and your data: You can get more information about the usage of your data, the storage of your registration, sending out mails with the US-provider ConvertKit, statistical analysis of emails sent and your possibility to unsubscribe in my Privacy Policy.

I use the US-provider ConvertKit for email automation. By clicking to submit this form, you acknowledge that the information you provide will be transferred to ConvertKit for processing in accordance with their Privacy Policy and Terms.

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit