DocsHub
JavascriptBeginner

Random Color Generator

Build a random color generator that creates a new color on every click and displays its hex code.

Random Color Generator

Problem

Build a color generator where the user clicks a button and the background color of the page changes to a random color. The hex code of the new color is displayed on the screen.

User clicks button
Background changes to: #3a7bd5
Hex code shown: #3a7bd5

User clicks again
Background changes to: #e74c3c
Hex code shown: #e74c3c

User clicks again
Background changes to: #2ecc71
Hex code shown: #2ecc71

Logic

  1. Select the button and the hex code display element
  2. Listen for a click event on the button
  3. Generate a random number between 0 and 16777215 (which is #ffffff in decimal)
  4. Convert that number to a hexadecimal string
  5. Pad with leading zeros if needed — hex color must always be 6 characters
  6. Apply the color to the page background
  7. Display the hex code on screen

Flow

User clicks button Generate random number0 to 16777215 Convert to hex string Pad to 6 characters Add # prefix Apply to body background Show hex code on screen

HTML Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Random Color Generator</title>
    <style>
      body {
        font-family: sans-serif;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        margin: 0;
        /* background will be changed by JavaScript */
        background-color: #ffffff;
        /* smooth transition between colors */
        transition: background-color 0.4s ease;
      }

      /* box showing the current hex code */
      #color-display {
        font-size: 2.5rem;
        font-weight: 700;
        letter-spacing: 2px;
        margin-bottom: 32px;
        /* color will be updated by JS so it stays readable */
        color: #111;
      }

      button {
        padding: 14px 32px;
        font-size: 1rem;
        font-weight: 600;
        background: #111;
        color: #fff;
        border: none;
        border-radius: 8px;
        cursor: pointer;
      }

      button:hover {
        opacity: 0.85;
      }
    </style>
  </head>
  <body>

    <!-- shows the current hex color code -->
    <div id="color-display">#ffffff</div>

    <!-- click to generate a new color -->
    <button id="generate-btn">Generate Color</button>

    <script src="script.js"></script>
  </body>
</html>

Solution

// Step 1 — select the elements we need
const generateBtn = document.querySelector("#generate-btn");
const colorDisplay = document.querySelector("#color-display");

// Step 2 — listen for click on the button
generateBtn.addEventListener("click", generateColor);

function generateColor() {
  // Step 3 — generate a random integer between 0 and 16777215
  // 16777215 is 0xFFFFFF in decimal — the highest possible hex color
  const randomNumber = Math.floor(Math.random() * 16777216);

  // Step 4 — convert the number to a hexadecimal string
  // toString(16) converts a number to base 16 (hexadecimal)
  // example: 255 → "ff", 0 → "0", 16777215 → "ffffff"
  const hexString = randomNumber.toString(16);

  // Step 5 — pad the string to always be 6 characters
  // padStart(6, "0") adds leading zeros if the string is shorter than 6
  // example: "ff" → "0000ff", "fff" → "000fff"
  const hexColor = "#" + hexString.padStart(6, "0");

  // Step 6 — apply the color to the page background
  document.body.style.backgroundColor = hexColor;

  // Step 7 — update the hex code display
  colorDisplay.textContent = hexColor;

  // Step 8 — adjust text color for readability
  // dark background → white text, light background → dark text
  // we check brightness using the red, green, blue values
  const r = parseInt(hexColor.slice(1, 3), 16); // red value 0-255
  const g = parseInt(hexColor.slice(3, 5), 16); // green value 0-255
  const b = parseInt(hexColor.slice(5, 7), 16); // blue value 0-255

  // standard brightness formula — weighted average of RGB
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;

  // if brightness is less than 128 — background is dark, use white text
  colorDisplay.style.color = brightness < 128 ? "#ffffff" : "#111111";
}

Code Execution

Trace through one button click:

StepCodeResult
Random numberMath.floor(Math.random() * 16777216)3833301 (example)
To hex(3833301).toString(16)"3a7bd5"
Pad to 6"3a7bd5".padStart(6, "0")"3a7bd5" (already 6)
Add prefix"#" + "3a7bd5""#3a7bd5"
Apply backgrounddocument.body.style.backgroundColorpage turns blue
Show hexcolorDisplay.textContent#3a7bd5

Trace through a very small number where padding is needed:

StepCodeResult
Random numberMath.floor(Math.random() * 16777216)255
To hex(255).toString(16)"ff"
Pad to 6"ff".padStart(6, "0")"0000ff"
Add prefix"#" + "0000ff""#0000ff"
Apply backgrounddocument.body.style.backgroundColorpage turns blue

Brightness check for #3a7bd5:

StepCodeResult
RedparseInt("3a", 16)58
GreenparseInt("7b", 16)123
BlueparseInt("d5", 16)213
Brightness(58×299 + 123×587 + 213×114) / 1000107
Check107 < 128 → dark backgroundtext color = #ffffff

Output

Click 1 → Background: #3a7bd5   Hex shown: #3a7bd5   (white text)
Click 2 → Background: #f1c40f   Hex shown: #f1c40f   (dark text)
Click 3 → Background: #0000ff   Hex shown: #0000ff   (white text)

On this page