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.

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