Learn how to create a random color generator using only HTML, CSS and JavaScript
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Color Code: <span id="colorCode"></span></p>
<button type="button" id="randomColorBtn">Random Color</button>
<script src="script.js"></script>
</body>
</html>
CSS
*{
margin: 0;
padding: 0;
}
body{
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
font-size: 32px;
}
body button{
font-size: 24px;
}
JavaScript
let randomColorBtn = document.getElementById('randomColorBtn');
let colorCodeDisplay = document.getElementById('colorCode');
let hexValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
randomColorBtn.addEventListener('click', generateColor);
function generateColor(){
let colorCode = '#';
for(i = 0; i < 6; i++){
let random = Math.floor(Math.random()*hexValues.length);
colorCode += hexValues[random];
}
colorCodeDisplay.innerHTML = colorCode;
document.body.style.backgroundColor = colorCode;
}
If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on
YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ
Instagram: https://www.instagram.com/coding_for_the_web/
Twitter: https://twitter.com/LearnWebCoding
Comments