To generate a random color using JavaScript, the simplest way is to use the JavaScript random() method along with the Math.floor() and toString() methods.
var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
We can wrap this code in a function so that we can reuse this function anytime we want a new random color.
function randomColor(){
return ("#" + (Math.floor(Math.random()*16777215).toString(16)));
};
Let’s break down the code above.
First, you will notice we use the random() method which will return a float between 0 and 1. We multiply this by the number 16777215 because that is the total possible combinations of RGB(255,255,255).
We use the Math.floor() method to round our float down to an Integer. We finally use the toString() method with base 16 to convert our number to a hex. We add # to the front of our hex so that the color is ready to use.
Generating a Random Color on Click Using JavaScript
To generate a random color on click using JavaScript, we can combine our randomColor() function above with a click event.
Let’s say we have the following HTML, and we want to give the user the ability to generate a random color and show the random color in a div box below.
Generate random color
We can utilize the onclick event, Math random() method, the Math floor() method, and the toString method to generate a random color and show it to the user.
We will finally use the backgroundColor property to change the background color of our box div.
Below is the JavaScript code which will allow the user to be able to update the background color of the box with a randomly generated color.
function randomColor(){
var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
document.getElementById("box").style.backgroundColor = randomColor;
};
The final code and output for this example of how to generate a random color on click using JavaScript is below:
Code Output:
Full Code:
Generate random color
Hopefully this article has been useful for you to understand how to generate a random color using Javascript.