How to develop a Random Color Generator using JavaScript?
Creating a Random Colour Generator: HTML, CSS & JS
Table of contents
In this article i will help you develop a simple web project titled Random Color Generator using HTML, CSS and JavaScript.
Final Output
Youtube Video
For detailed explanation of code watch below video.
Code
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Random Color Generator</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Random Color Generator</h1>
<section><div id="parent-container" class="container"></div></section>
<footer>
<p>
Designed & Developed By:
<a href="#" style="text-decoration: none">Shubham Lashkan</a>
</p>
</footer>
<script src="script.js"></script>
</body>
</html>
CSS
h1 {
font-family: sans-serif;
font-size: 36px;
color: orange;
text-align: center;
}
p {
text-align: center;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.palette {
padding: 50px;
margin: 5px;
width: 200px;
text-align: center;
font-size: 24px;
border: 2px solid white;
border-radius: 15px;
color: white;
}
JavaScript
let parentContainer = document.getElementById("parent-container");
for (let i = 0; i < 40; i++) {
let code = randomColor();
let palette = document.createElement("div");
palette.className = "palette";
palette.style.backgroundColor = "#" + code;
palette.innerText = "#" + code;
parentContainer.appendChild(palette);
palette.addEventListener("click", function () {
navigator.clipboard.writeText(`#${code}`);
});
}
function randomColor() {
const hexChar = "0123456789ABCDEF";
const codeLength = 6;
let hexCode = "";
for (let i = 0; i < codeLength; i++) {
let randomIndex = Math.floor(Math.random() * 16);
hexCode = hexCode + hexChar.charAt(randomIndex);
}
return hexCode;
}
I hope you find this article helpful.
Please don't forget to like, comment and share and you can also check out my other articles. Also, don't forget to subscribe to my newsletter so you can be notified about new articles.
I am looking to get into technical writing so if you want me to write an article then please connect with me on my Twitter handle here.
Let me also know which topic I should write about next.
ย