Home > Tips & Tricks > Generate a Random Color in JavaScript

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 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment