Preplp
HTML CSS JS Projects
Project 1HTML · CSS · JS~45 min

Random Color Generator

DOM, loops, and the Clipboard API

Track progress0/3 days
x

What you'll learn

HTML structureCSS FlexboxcreateElementMath.random()clipboard
  • Build a grid of color cards with JavaScript
  • Generate random hex color codes
  • Style cards dynamically with inline background colors
  • Copy a color code to the clipboard on button click

Lesson & examples

Read the code, then the explanation — try changing values before the project.

Create elements in JS
const div = document.createElement("div");
div.classList.add("color-container");
document.querySelector(".container").appendChild(div);

The DOM is a tree. createElement builds a node; appendChild attaches it to .container on the page.

  • createElement

    Creates an empty <div> in memory — not visible until appended.

  • classList.add

    Applies CSS class names from style.css.

Random hex digit
const chars = "0123456789ABCDEF";
const randomNum = Math.floor(Math.random() * chars.length);
const digit = chars.substring(randomNum, randomNum + 1);

Math.random() gives 0–1. Multiply by length and floor to get a valid index into the hex character string.

Set background from JS
colorContainerEl.style.backgroundColor = "#" + newColorCode;

Inline styles override CSS. Here the card background becomes whatever hex code you generated.

Today's project: Random Color Generator

Display 50 color swatches. Each shows its hex code and a Copy button. Colors are generated when the page loads.

Open index.html in your browser (Live Server in VS Code works great).

Steps

  1. 1

    HTML skeleton

    Add a heading and an empty div.container. Link style.css and script.js.

  2. 2

    Style the grid

    Use flexbox with wrap on .container. Style .color-container as square cards with centered text and a button.

  3. 3

    Generate 50 cards

    Loop 50 times: create a div, span for the hex code, and a Copy button. Append each to .container.

  4. 4

    Assign random colors

    Write randomColor() to build a 6-character hex string. Loop all cards and set background + span text to #XXXXXX.

  5. 5

    Copy to clipboard

    On each Copy click, read the span text and use navigator.clipboard.writeText().

Full project source — copy into a folder or use the zip above

Open index.html in your browser (Live Server in VS Code works great).

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random Color Generator</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Random Color Generator</h1>
  <div class="container"></div>
  <script src="script.js"></script>
</body>
</html>

Empty .container is filled entirely by JavaScript — classic pattern for dynamic UIs.

style.css
body {
  margin: 0;
  padding: 0;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

h1 {
  text-align: center;
  text-decoration: underline;
}

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.color-container {
  width: 200px;
  height: 200px;
  color: #fff;
  margin: 5px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 25px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  border: solid black 2px;
  border-radius: 5px;
}

button {
  background-color: #ff1493;
  border: none;
  border-radius: 3px;
  padding: 8px 16px;
  margin-top: 15px;
  cursor: pointer;
}

button:hover {
  background-color: #ff0055;
}

Flexbox on .container wraps cards into a grid. .color-container sets size; JS will override background-color per card.

script.js
const containerEl = document.querySelector(".container");

for (let index = 0; index < 50; index++) {
  const colorContainerEl = document.createElement("div");
  colorContainerEl.classList.add("color-container");

  const colorCodeEl = document.createElement("span");
  colorCodeEl.classList.add("color-code");
  colorContainerEl.appendChild(colorCodeEl);

  const copyButtonEl = document.createElement("button");
  copyButtonEl.innerText = "Copy";
  colorContainerEl.appendChild(copyButtonEl);

  containerEl.appendChild(colorContainerEl);
}

function randomColor() {
  const chars = "0123456789ABCDEF";
  let colorCode = "";
  for (let i = 0; i < 6; i++) {
    const randomNum = Math.floor(Math.random() * chars.length);
    colorCode += chars.substring(randomNum, randomNum + 1);
  }
  return colorCode;
}

const mainColorContainerEls = document.querySelectorAll(".color-container");

function generateColors() {
  for (let i = 0; i < mainColorContainerEls.length; i++) {
    const colorContainerEl = mainColorContainerEls[i];
    const newColorCode = randomColor();
    const colorCodeEl = colorContainerEl.querySelector(".color-code");
    colorContainerEl.style.backgroundColor = "#" + newColorCode;
    colorCodeEl.innerText = "#" + newColorCode;
  }
}

generateColors();

mainColorContainerEls.forEach((colorContainerEl) => {
  const copyButtonEl = colorContainerEl.querySelector("button");
  const colorCodeEl = colorContainerEl.querySelector(".color-code");

  copyButtonEl.addEventListener("click", () => {
    const colorCode = colorCodeEl.innerText;
    navigator.clipboard.writeText(colorCode).then(() => {
      alert("Copied to clipboard: " + colorCode);
    });
  });
});

Three phases: build 50 cards, paint random colors, attach copy listeners. querySelectorAll grabs every card after creation.

Code explained

  1. 1.Build loop (50 cards)

    The first for-loop only creates structure — div, span, button — and appends to the container. No colors yet.

    Snippet
    for (let index = 0; index < 50; index++) {
      // createElement + appendChild
    }
  2. 2.randomColor()

    Six iterations pick random hex digits. substring(randomNum, randomNum + 1) grabs one character at that index.

  3. 3.Clipboard API

    navigator.clipboard.writeText runs in a secure context (localhost or https). The alert confirms success for learners.

Sample output

A grid of 50 colored squares, each showing a hex code like #A3F21B and a Copy button.

One rehearsal platform

Certification mocks, daily lessons, project labs, and in-browser drills

Structured for exam day and portfolio proof — timed tests, guided builds, and quick reps on one platform.