DEV Community

Ahmed Zougari
Ahmed Zougari

Posted on • Edited on

How to generate random color with JavaScript

Today we gonna learn how to generate a random color using JavaScript with a few lines :

1-Generate random integer between 0 and 15

first we need to know how to get a random number

let randomNumber = Math.random();
//return random number between 0 and 1 (0.46578483)
Enter fullscreen mode Exit fullscreen mode

but we don’t want this result, we need random number integer between 0 and 15
To have it we have use you Math.floor()

let randomNumber = Math.floor(Math.random()*16);
//return random integer between 0 and 15
Enter fullscreen mode Exit fullscreen mode

2-Why 0 and 15 ?

Well this is the length of an array that contains all alphanumeric of HEX code, and we want to select random index 6 times and join all in one string.
( In this example we will use the HEX code, 0 to 9 and a to f
Ex: #E06910 , #02198C, #BADA55)

const hexArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
Enter fullscreen mode Exit fullscreen mode

3-Get random HEX code

we need to loop 6 times and concatenate the result every time to the code string

let code = "";
for(let i=0; i<6; i++){
 code += hexArray[Math.floor(Math.random()*16)];
}
//don' forget the code start with "#"
code = `#${code}`;
Enter fullscreen mode Exit fullscreen mode

4-Make your code inside function

now we need to write our code in function to use it perfectly

function generateColor(){
 const hexArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
 let code = "";
 for(let i=0; i<6; i++){
  code += hexArray[Math.floor(Math.random()*16)];
 }
 return `#${code}`
}
Enter fullscreen mode Exit fullscreen mode

In this example I use it in the body background:

document.body.style.backgroundColor = generateColor();
Enter fullscreen mode Exit fullscreen mode

live demo :

Thanks for reading

I hope you find that useful, if you want to practice more you can create your own function to generate random RGB or HSL color .

Top comments (2)

Collapse
 
sephiga profile image
Sephiga

Thank you so much for this. It really helps a lot as a beginner

Collapse
 
zougari47 profile image
Ahmed Zougari

Glad it helps.