Whether you’re a beginner or an experienced developer, this guide will help you generate random color with JavaScript to your web projects in new and exciting ways.
Preview (Generate Random Color with JavaScript)

HTML
For this project of generate color with JavaScript we only need 2 HTML elements. A <p>
tag with id of color
& a <button>
that can be used to generate a onClick event.
<p id='color'></p>
<button>Generate</button>
CSS
Align the HTML Center to the center of the page by using display:flex
& align-items: center
@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
font-family: 'Open Sans', sans-serif;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
transition: 0.2s;
}
button {
margin-top: 20px;
border: 0;
background: #eee;
color: #000;
padding: 12px 20px;
box-shadow: 0px 4px 8px rgba(0,0,0,0.3);
}
button:focus, button:active {
outline:none;
}
p {
font-size: 32px;
}
JavaScript
let text = document.querySelector("#color");
document.querySelector("button").addEventListener("click", () => {
let colorletter = "";
let letters = '0123456789ABCDEF';
for (var i = 0; i < 6; i++) {
colorletter += letters[Math.floor(Math.random() * 16)];
}
let color = "#" + colorletter;
// Use the color wherever you want to use.
text.innerHTML = color;
document.body.style.background = color;
})
Each time the JavaScript button is clicked it fires a click
event. It has a function executed when the click event triggers. A for..loop uses Math.random()
which fetches letters from the letters
& After running the loop 6 times. add the #
to that 6 letter random word, to format it like a HEX Color. You can now use this color in your website anywhere you can.
Here is the Github repository link: https://github.com/code-architects/generate-random-hex-color
This project was a part of our 15 Days – 15 Projects series. Read more projects 👇
- Create beautiful Profile Card with HTML & CSS
- Star Rating with HTML and CSS
- Social Share Buttons/Links
Happy Coding 💞