Skip to content

Color Changer

Beginner ~10 min

What you'll build

A page with a colored box and a "Change color" button. Each click generates a random hex color and applies it to the box's background.

Goals

  • Generate a random hex color string
  • Update an element's inline style from JavaScript
  • Use a click event listener to trigger the update
  • Understand how CSS properties map to the style object

Prerequisites

  • String concatenation or template literals
  • DOM selection and event listeners

Steps

  1. 1

    Write the HTML

    Create a div with an id and a button. The div is the color target; the button triggers the change.

    Code
    <div id="box" style="width:200px;height:200px;background:#2563eb;"></div>
    <button id="change">Change color</button>

    Expected result

    A blue 200×200 box and a button appear on the page.

  2. 2

    Generate a random hex color

    Write a function that builds a hex color from six random hex digits. Each digit is 0-15, converted to hex with toString(16).

    Code
    function randomColor() {
      let hex = "#";
      for (let i = 0; i < 6; i++) {
        hex += Math.floor(Math.random() * 16).toString(16);
      }
      return hex;
    }

    Expected result

    Calling randomColor() returns strings like "#3f9a2c" — valid hex colors.

  3. 3

    Wire the button

    Select the box and button. On click, set box.style.background to a new random color. The style object maps directly to CSS properties.

    Code
    const box = document.getElementById("box");
    const btn = document.getElementById("change");
    
    btn.addEventListener("click", () => {
      box.style.background = randomColor();
    });

    Expected result

    Each click changes the box to a new random color.

  4. 4

    Add input validation & error handling

    Add validation at user input points: check for empty values, non-numbers, negatives, and other anomalies, using try/catch or conditionals to show friendly messages. Robust JS programs don't crash on unexpected input.

    Code
    function safeParse(value) {
      if (value === null || value === undefined || value === "") {
        throw new Error("Input is empty");
      }
      const num = Number(value);
      if (Number.isNaN(num)) {
        throw new Error(`"${value}" is not a valid number`);
      }
      return num;
    }
    
    try {
      const n = safeParse(userInput);
      process(n);
    } catch (err) {
      console.error(err.message);
    }

    Expected result

    Empty or non-number input shows an error message instead of crashing; valid numbers process normally.

  5. 5

    Add event listeners & interaction

    Bind event listeners (click, input, keydown, etc.) to page elements so the program responds to user actions. Interactivity is the core value of JavaScript in the front end.

    Code
    const button = document.querySelector("#action-btn");
    const input = document.querySelector("#user-input");
    
    button.addEventListener("click", () => {
      const value = input.value.trim();
      if (!value) return;
      runMainLogic(value);
    });
    
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") button.click();
    });

    Expected result

    Clicking the button or pressing Enter triggers the main logic; empty input is ignored.

Try it yourself

What you learned

You generated a random hex string and applied it via the element's style object — the same approach used by any tool that changes appearance from JavaScript.

Related Resources

Related Lessons

  • DOM

    The click listener that triggers the color change.

  • Data Types

    Building the hex string with concatenation.

Related Practice

Related Tools

  • Color Tool

    Inspect and convert the hex colors your generator produces.

Related Cheatsheets

Related Reference

Related Errors

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Related Errors

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

← Back to topic