After recently delving into the world of JavaScript, I decided to create a background color generator that randomly changes when a button is clicked. This simple project involves two input fields (color1 & color2) which receive random values upon clicking the button, updating the body's style accordingly.
Here's the code: HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Gradient Background</title>
</head>
<body id="gradient">
<div class="container">
<h1>Background Generator</h1>
<input class="color1" id="color1" type="color" name="color1" value="#ff0000">
<input class="color2" id="color2" type="color" name="color2" value="#ffff00">
<h2>Current CSS Background</h2>
<h3></h3>
<button id="button" class="button">Randomize</button>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript:
var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById("gradient");
var button = document.getElementById("button");
var inputColor1 = document.getElementById("color1");
var inputColor2 = document.getElementById("color2");
function setGradient() {
body.style.background = "linear-gradient(to right," + color1.value + "," + color2.value + ")";
css.textContent = body.style.background + ";";
}
color1.addEventListener("input", setGradient);
color2.addEventListener("input", setGradient);
inputColor1.value = generateRandomColor().value;
inputColor2.value = generateRandomColor().value;
function generateRandomColor(){
let maxVal = 0xFFFFFF; // 16777215
let randomNumber = Math.random() * maxVal;
randomNumber = Math.floor(randomNumber);
randomNumber = randomNumber.toString(16);
let randColor = randomNumber.padStart(6, 0);
return `#${randColor.toUpperCase()}`
}
// console.log(generateRandomColor());
button.addEventListener("click", generateRandomColor);
Thanks ;)