Generate random Hex color

function genHexColor() { return '#' + (Math.random() * (1<<24) | 0).toString(16); }
Call the genHexColor() function to obtain a random color in Hex format.
///
Latest version: Prevents the function from returning hex strings shorter than 6 characters.

5 Responses

shorter one~
`'#' + (Math.random() * (1<<24) | 0).toString(16)`
@Rplus That is an absolute amazing trick! Thanks!
@Rplus Yeah but it'd end up with missing 0 digits sometimes, I tried it in the nodejs console.
@Luis Lopez It did! Good point, @Luis Lopez! So I made a new version, and this one automatically adds zeroes <i>.concat('000000')</i> and then truncates whatever is too much <i>.slice(0,6);</i>. The last version is fool-proof!

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.