DEV Community

Cover image for Build a Random Background Color Changer with JavaScript
Megha M
Megha M

Posted on

Build a Random Background Color Changer with JavaScript

Hey everyone I have created a Random Background Color Changer using JavaScript. This is a fun beginner-friendly project that changes the background color of the webpage every time you click a button.

What I Did

  • Created a simple HTML page with a button.
  • Wrote a JavaScript function that generates random HEX color codes.
  • Applied that random color to the background of the page when the button is clicked.

Steps I Followed

HTML Structure

  • Added a that calls the changecolor() function when clicked.
  • Gave the an id so we can easily target it in JavaScript.

Define HEX Digits

  • HEX colors are made from numbers 0–9 and letters A–F.
  • I stored them in an array called color.

Random Generator Function

  • Wrote a random() function that picks a random digit from the array.

Build a HEX Code

  • Started with #.
  • Used a loop to add 6 random characters to form a complete HEX code (like #12ABF3).

Change Background Color

Used document.querySelector("#body").style.backgroundColor = hexa;

This updates the background color each time the button is clicked.

How It Works

  • You click the button.
  • JavaScript runs the changecolor() function.
  • A random HEX color is generated.
  • The color is applied as the new background of the webpage.

Every click gives a fresh new color

Top comments (0)