pixelwright UI Development & Design

Random Hex colours using Javascript

Here is a quick and short way to generate random #Hex colours using Javascript:

Code

'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);

// To use a string (such as user_id) for a unique colour:


function stringToColorCode(str) {
    return (str in color_codes) ? color_codes[str] : (color_codes[str] = '#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6));
}

Questions?

Have a question about this post, a project or anything else?
Let's have a conversation on Twitter.