JavaScript - 24

JavaScript - 24: Random Background Color Changer

Create a small color changer that gives the page a random background color and displays the color code.

Your challenge: Generate a random hex color, apply it to the page, and add a Reset button that returns the background to black.

✦ JavaScript Editor
▶ Live Output

Build a hex color

Hex colors use six characters after #, such as: #4A8FD2

The string: "0123456789ABCDEF" contains all the characters you need.

Choose a random character

Use: Math.random() to generate a random decimal number.

Then: Math.floor(Math.random() * 16) creates a random index from 0 to 15.

A for loop can repeat this six times to build the color.

Change the background

After getting a color, apply it with: document.body.style.backgroundColor = newColor;

Then update the visible code using .textContent.

Reset the page

The Reset button should set the background and displayed color back to: #000000

Try it: Click Change Color several times and watch the hex code change with the background.

Good JavaScript habit: Put repeated logic such as generating a random color inside a function so you can reuse it whenever needed.

👀 Show Solution
function getRandomColor() {
  const letters = "0123456789ABCDEF";
  let color = "#";

  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }

  return color;
}

const changeBtn = document.getElementById("changeBtn");
const resetBtn = document.getElementById("resetBtn");
const colorCode = document.getElementById("colorCode");

changeBtn.addEventListener("click", function() {
  const newColor = getRandomColor();

  document.body.style.backgroundColor = newColor;
  colorCode.textContent = newColor;
});

resetBtn.addEventListener("click", function() {
  document.body.style.backgroundColor = "#000000";
  colorCode.textContent = "#000000";
});

The loop builds a six-character hex color. The Change button applies it to the page, while the Reset button restores the original black background.