Random Color Generator using HTML | CSS | JS
This is a simple web application where we can generate random colors by one
click and display RGB values of current colors on the screen.
We will use Math.random() function to generate random integers and
Math.floor() to get floor value of the number.
Please follow the below code and get started 💻.
HTML Code
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Background</title>
<!-- css link -->
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<!-- button to generate random colors -->
<button class="btn" id="btn">Click me!</button>
<!-- show color here -->
<h3 class="show" id="show"></h3>
<!-- javascript link -->
<script src="./app.js"></script>
</body>
</html>
CSS Code
style.css
:root{
--light: #fff;
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
min-height: 100vh;
background: #f1f2f3;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
transition: 1s ease;
font-family: sans-serif;
}
.btn{
background: #222;
color: var(--light);
padding: 14px 30px;
font-size: 1.2rem;
letter-spacing: 1px;
font-family: sans-serif;
border-radius: 25px;
border: none;
outline: none;
box-shadow: 0 4px 8px rgba(0,0,0,.4);
cursor: pointer;
transition: .2s ease;
}
.btn:hover{
background: #333;
}
.show{
margin-top: 20px;
font-size: 3em;
font-weight: 200;
letter-spacing: 1px;
}
.btn:active{
transform: scale(0.97);
}
JavaScript Code
app.js
// selectors
const btn = document.getElementById('btn');
const show = document.getElementById('show')
btn.addEventListener('click', () => {
// generate random number between 0 to 255
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let color = `rgb(${r}, ${g}, ${b})`;
document.body.style.background = color;
show.innerText = color;
});
Output
That is all! I hope you find this interesting and helpful. Thank you for visiting my blog.
Code by - AltafAlam Shaikh
Topic covered - random() and floor() function in javascript
Technology used - Html, Css, JavaScript