Color Changer
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
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
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).
Codefunction 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.
Hint
toString(16) converts a number 0-15 to a single hex digit (0-9 or a-f).
- 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.
Codeconst 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
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.
Codefunction 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
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.
Codeconst 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
<div id="box" style="width:200px;height:200px;background:#2563eb;"></div>
<button id="change">Change color</button>
<script>
// TODO: randomColor() + wire button
</script><div id="box" style="width:200px;height:200px;background:#2563eb;"></div>
<button id="change">Change color</button>
<script>
function randomColor() {
let hex = "#";
for (let i = 0; i < 6; i++) {
hex += Math.floor(Math.random() * 16).toString(16);
}
return hex;
}
const box = document.getElementById("box");
const btn = document.getElementById("change");
btn.addEventListener("click", () => {
box.style.background = randomColor();
});
</script>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
- DOM Events MCQ
Quiz on event listeners and the style object.
- Strings Predict
Predict the result of string concatenation.
Related Tools
- Color Tool
Inspect and convert the hex colors your generator produces.
Related Cheatsheets
- JavaScript Cheatsheet
Math, string, and DOM style syntax reference.
Related Reference
- JavaScript String Methods
Complete string method reference.
Related Errors
- Cannot Read Properties of Null
Null element selection mistakes.
Related Glossary
- DOM
Document Object Model basics.
- Event
User and system events.
- Event Listener
Handling events in JS.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
- DOM
Document Object Model basics.
- Event
User and system events.
- Event Listener
Handling events in JS.
Related Errors
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
- Cannot Read Properties of Null
Null element selection mistakes.