How do I randomly generate HTML hex color codes using 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');

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.

Tags:

Javascript