Generate a Random Color in JavaScript

In this trick, we will see how we can generate the random number in javascript and make a random color code from it.

We will use the Math.floor(), Math.random() and toString() methods. The Math.floor() method is used to round the number down to the nearest, the Math.random() method is used to generate the random number, and the toString() method used to convert the string object to string.

Generate Random Color in JavaScript

We will make a function with logic to use these methods to return a 6-digit of random numbers because the hex color code is in 6-digit numbers format. See the following javascript code snippet to generate the random color.

So in the above code, we take an <p> element with the id of “color” and then take a button to generate the color with onclick() function.

Then made a randomColor() function using the Math functions and set the generated color to the body background and also show it in the <p> element.

That’s it!!!

Being Tricky 😉

Leave a Reply

Your email address will not be published. Required fields are marked *