How do I randomly generate HTML hex color codes using JavaScript?

Javascript

Javascript Problem Overview


> Possible Duplicate:
> Random Color generator in Javascript

I have some data I'd like to display in different colors and I want to generate the colors randomly if possible. How can I generate the Hex Color Code using JavaScript?

Javascript Solutions


Solution 1 - Javascript

This will generate a random number within the bounds and convert it to hexadecimal. It is then padded with zeros so that it's always a valid six-digit hex code.

'#'+(Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0');

Solution 2 - Javascript

There are a variety of methods in the blog post Random hex color code generator in JavaScript. You need to pad with zeros when the random value is less than 0×100000, so here's the correct version:

var randomColor = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});

That replaces each of six 0s with a random hex digit, so it's sure to end up with a full six-digit valid color value.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAchillesView Question on Stackoverflow
Solution 1 - JavascriptDanSView Answer on Stackoverflow
Solution 2 - JavascriptBill the LizardView Answer on Stackoverflow