99

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?

Community
  • 1
  • 1
Achilles
  • 11,165
  • 9
  • 62
  • 113

2 Answers2

221

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');
aravk33
  • 469
  • 2
  • 10
  • 18
DanS
  • 17,550
  • 9
  • 53
  • 47
  • 24
    note that this method outputs wrong color codes, too: `> '#'+(.001*0xffffff<<0).toString(16) ---> '#4189'` – Scheintod Jan 06 '16 at 14:21
  • 6
    I don't prefer shorthand ways. A boring longhand way would be a lot clearer about what is going on. If I saw this code by itself, it would take me a long time to connect it with its express purpose. – Christos Hayward Mar 26 '16 at 21:51
  • 2
    I used then it shows some error at some point. please use the accepted answer here https://stackoverflow.com/questions/1484506/random-color-generator – Gilbert Mendoza Jun 29 '17 at 08:13
  • 1
    Like @Scheintod said, this occasionally produces wrong values. I just got `#c5935` – AmmarCSE Nov 21 '18 at 08:07
  • @adjenks your edit is a completely different answer. You should post it as its own answer, not an edit that removes all of someone else's code. – camille Mar 28 '19 at 21:40
  • @camille I suppose, but.. It's gone now... Oh well... – ADJenks Mar 28 '19 at 22:44
  • Also, I cannot add an answer here because it's locked. I liked the solution but I wanted to fix the problem that Scheintod pointed out. I edited again, but a bit less radically. – ADJenks Mar 29 '19 at 00:47
  • @MarredCheese Really? I can't make the code less buggy? I think that my edit does actually "strive to preserve the goals of the post's owner." – ADJenks Mar 29 '19 at 17:31
  • Where can we find the explanation of your code? Can you give details/explanation why ` * 0xFFFFFF << 0` to get a hex value? – m3.b Nov 27 '21 at 00:57
109

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880