DEV Community

Cover image for JavaScript Project: Random Hex Color Generator
s mathavi
s mathavi

Posted on

JavaScript Project: Random Hex Color Generator

HTML Setup

  • Used a simple HTML structure with a <button> inside a centered <div> container.
  • Title is set as ColorFlipper.

CSS Styling

  • Full height body with no margin.
  • Flexbox (display: flex; justify-content: center; align-items: center;) to center the button.
  • Styled button with padding, font-size, border-radius, background, and hover pointer.

DOM Selection
Selected the button using document.querySelector('button').

Event Listener
-Attached a click event listener:
btn.addEventListener('click', colorChanging);
-So every time the button is clicked, background color changes.

Color Array
Created an array of hexadecimal digits:
let color=[0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"];
This is the building block for generating hex color codes.

Random Generator Function

  • Wrote a helper function random() that:
  • Uses Math.random() to generate a random number.
  • Multiplies it by array length.
  • Uses Math.floor() to round it down to an integer.
  • Returns one random item from the array.

Hex Code Creation
In colorChanging() function:

  • Started with let hexa = "#".
  • Used a for loop to run 6 times (since a hex code has 6 characters).
  • Appended 6 random values from the color array to form something like #3A5F9C.

Apply New Color
Set the body background to the new hex code:
document.querySelector('body').style.backgroundColor = hexa;

!!......That’s it! We just built a simple yet cool JavaScript Color Flipper using DOM, events, and randomness.....!!
Thanks for reading, and I’ll be back with another fun JavaScript project.
See you soon!

Top comments (0)