Generate Random Color in Javascript

July 25, 2020

#Javascript #Colors

The final result

Hit the Generate random color button !

Some Details

Generating a random color is like generating a random hexadecimal number.
Colors in CSS are represented by an hex number of 6 digits : the highest number is #ffffff which is the white color, the lowest is the black color #000000.
So every color is placed between the black and the white. Given that , you can take a number less than #ffffff and you have a color.

The code

function generateRandomColor() {

var whiteHex = parseInt('ffffff', 16); // Convert the white hex string to a base16 number
var color = Math.floor(Math.random()*whiteHex).toString(16);  // Convert random integer to hex string

return '#' +color;
}

console.log(generateRandomColor()); // #250322

You can also look at the code snippet that I used for the example, by clicking on the “Javascript” tab of the JFiddle box at the top of the page.
Hope you enjoy this post,

Pingu 🐧


Written by Pingu who lives and works in Genoa building useful modern applications.

Something to share ?