Here’s a quick, self-contained webpage.
Drop the whole thing into a file named index.html, open it in a browser, and click the button to watch the background color change. 🚀
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Color-Flip Background</title>
<!-- Tiny bit of styling just to center things -->
<style>
body {
margin: 0;
height: 100vh; /* fill the whole viewport */
display: flex;
align-items: center;
justify-content: center;
background: #f0f0f0; /* initial color */
font-family: system-ui, sans-serif;
transition: background 0.4s; /* smooth fade */
}
button {
padding: 1rem 2rem;
font-size: 1.1rem;
border: none;
border-radius: 8px;
background: #333;
color: #fff;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #555;
}
</style>
</head>
<body>
<button id="colorBtn">Change Background Color</button>
<script>
// Array of colors we’ll cycle through
const colors = ["#f9c74f", "#90be6d", "#577590", "#f94144", "#f3722c", "#43aa8b"];
let current = 0;
document.getElementById("colorBtn").addEventListener("click", () => {
// Pick the next color in the list (looping back to start)
current = (current + 1) % colors.length;
document.body.style.backgroundColor = colors[current];
});
</script>
</body>
</html>
How it works (super-quick rundown):
- We preload six hex colors in the
colors array.
- Each button click increments an index (
current) and sets document.body.style.backgroundColor to the new value.
- CSS
transition on body gives us the nice fade between colors.
Feel free to swap out the colors, randomize instead of cycling, or jazz up the button as you like. Have fun! 🎨