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 :
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.
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 🙂