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 0
s with a random hex digit, so it's sure to end up with a full six-digit valid color value.