How To Generate Random Colors in JavaScript

Did you ever feel bored of writing long codes to generate random colors for different divs or any other tags just to test something simple?

So here is a simple and full stop solution. The following snippet generates a random color in hexadecimal format. it takes just takes a single line.

var genrateRandomColor = '#'+Math.floor(Math.random()*16777215).toString(16);

Here is the example :

Random Color Change

In the above example, you can observe by clicking the “Generate New Color” button and the DIV gets automatically changes its color and  here you can find the answer for your Question “how to generate random color in javascript”

You can directly download the file by clicking here

Code Explanation :

Very firstly we are creating a Div, where the color should change OnClick of the button. After that we adding a button with OnClick functionality as you can see in the below code.

//creating a Div

<div id="clorChangeDiv">

<input type="button" onclick="generateRandomColor()" value="Generate New Color">

//Above is the button with onclick attribute

So, our HTML is ready fire.

The next step is to create JS for this.

//JavaScript to change the color of a Div

<script type="text/javascript">
function generateRandomColor()
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
var s = document.getElementById('clorChangeDiv'); = randomColor;

In the above JS we have created a variable called “randomColor” which store the “#” and con-cats the random digits. As we need some randomness in our output for colors, we are multiplying our number with Math.random() which returns a floating number in range from inclusive of 0 to exclusive of 1

That’s it!! you can use the function for your project or to your codes and you can call it anytime you need random numbers.

Happy Coding 🙂

About the author


A coder who is trying to solve some problems via "Procoders", Software Engineer By Profession, WEB Enthusiast, Hobby Blogger. I love to share Tech Ideas and like to learn and explore new things and Technologies.

Add Comment

Click here to post a comment