Back to Projects Beginner

Color Flipper

Click a button and the whole page changes to a random color. A visual and fun project — great for understanding how JavaScript changes CSS on the fly.

HTML, CSS, JavaScript ~1-2 hours to build Free source code

What You'll Learn

  • How to generate random numbers in JavaScript using Math.random()
  • How to build a random hex color code from scratch
  • How to change CSS styles of elements directly from JavaScript
  • How to display dynamic values on the page
  • How to handle click events with addEventListener()

How It Works

Random colors use hex codes

Web colors are written as 6-character hex codes like #FF5733. Each character can be 0-9 or A-F. We randomly pick 6 characters from that set to make a new color every click.

JavaScript changes CSS directly

JavaScript can reach into your HTML and change any CSS property in real time. We use document.body.style.background to swap the whole page background instantly.

The color code is shown on screen

We also update a text element to show the current hex code so users can copy colors they like!

Source Code

HTML Structure

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Color Flipper</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Color Flipper</h1>
    <p>Current color:</p>
    <h2 id="colorCode">#FFFFFF</h2>
    <button id="flipBtn">Flip Color</button>
  </div>
  <script src="script.js"></script>
</body>
</html>

CSS Styling

CSS
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
  min-height: 100vh; display: flex; align-items: center;
  justify-content: center; background: #ffffff;
  transition: background 0.5s ease;
  font-family: 'Segoe UI', sans-serif;
}
.container { text-align: center; }
h1 { font-size: 3rem; font-weight: 800; color: #25265e; margin-bottom: 8px; }
p { font-size: 1.1rem; color: #666; margin-bottom: 4px; }
h2 {
  font-size: 2.5rem; font-weight: 700; letter-spacing: 4px;
  margin-bottom: 32px; font-family: monospace; color: #25265e;
}
#flipBtn {
  padding: 16px 48px; font-size: 1.1rem; font-weight: 700;
  background: #25265e; color: white; border: none;
  border-radius: 50px; cursor: pointer; transition: all 0.3s;
}
#flipBtn:hover { background: #1a1b4b; transform: scale(1.05); }

JavaScript Logic

JavaScript
const hexChars = '0123456789ABCDEF';

function getRandomColor() {
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += hexChars[Math.floor(Math.random() * 16)];
  }
  return color;
}

document.getElementById('flipBtn').addEventListener('click', function() {
  const newColor = getRandomColor();
  document.body.style.background = newColor;
  document.getElementById('colorCode').textContent = newColor;
});

Download Source Code

Single ready-to-run HTML file. Open it in any browser instantly!

Download Project

Single HTML file · All code included