Would you like to practice JavaScript? Try building a random color generator! Let’s see in this article how to successfully complete this project.
![]()
Step 1
Let's start with our HTML code.
<div class="main">
<div id="code">#000000</div>
<button onclick="generateColor()">
Generate
</button>
</div>Here, we just need a button that calls a JavaScript function when clicked.
Step 2
Let's center our element in the middle of the page.
body {
background: #000000;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}We will use Flexbox to center the box that will allow us to generate a color.
Step 3
Now, let's take care of the box and the code class!
.main {
width: 350px;
height: 250px;
background: white;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
#code {
font-size: 3rem;
margin-bottom: 20px;
}
Step 4
Let's finish our design by styling the button.
.main button {
padding: 10px 20px;
font-size: 1.1rem;
border: none;
outline: none;
cursor: pointer;
background: #1687a7;
color: white;
}
Step 5
All that's left is to create the generateColor() function.
const generateColor = () => {
let randomColor = (Math.floor(Math.random()*0xFFFFFF)).toString(16);
document.body.style.backgroundColor = "#" + randomColor;
let text = document.querySelector('#code');
text.innerText = "#" + randomColor;
}To generate a random hexadecimal number, there is a ready-made formula. Simply generate a random number (between 0.0000... and 0.9999...) and multiply it by 0xFFFFFF, which is the largest possible number for a hexadecimal color.
We generally end up with a 6-digit number. All that's left is to round down this number (floor()) and convert it into a base 16 string (thus hexadecimal).
Finally, we just need to add this color.







