Simple color generator app in JavaScript

This random color generator app allows users to change the background color of the webpage with a single button click by generating a random hexadecimal color code; it uses JavaScript to create the color dynamically, apply it instantly to the page’s background, and display the generated color code on the screen, helping students understand core concepts such as functions, loops, random number generation, and basic DOM manipulation in a simple and visual way.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Sets character encoding so text displays correctly -->
  <meta charset="UTF-8">

  <!-- Title shown in browser tab -->
  <title>Color Generator</title>

  <style>
    /* Style for the whole page */
    body {
      font-family: Arial, sans-serif;     /* Font style */
      text-align: center;                 /* Center text */
      padding: 40px;                      /* Space around content */
      background-color: #ffffff;          /* Initial background color */
    }

    /* Style for the button */
    button {
      padding: 15px 20px;                 /* Button size */
      font-size: 16px;                    /* Text size */
      cursor: pointer;                    /* Hand cursor on hover */
    }

    /* Style for color text */
    #colorCode {
      margin-top: 20px;                   /* Space above text */
      font-size: 20px;                    /* Bigger text */
    }
  </style>
</head>

<body>

  <!-- Page heading -->
  <h1>Random Color Generator</h1>

  <!-- Button that triggers color change -->
  <button onclick="generateColor()">Generate Color</button>

  <!-- Paragraph to show color code -->
  <p id="colorCode">Color: #FFFFFF</p>

  <script>
    // Function that generates a random color
    function generateColor() {

      // Characters used in hexadecimal color codes
      const letters = "0123456789ABCDEF";

      // Starting value for color (must start with #)
      let color = "#";

      // Loop runs 6 times to create a 6-digit color code
      for (let i = 0; i < 6; i++) {

        // Pick a random character from letters
        color += letters[Math.floor(Math.random() * 16)];
      }

      // Change the page background color
      document.body.style.backgroundColor = color;

      // Display the color code on the screen
      document.getElementById("colorCode").textContent = "Color: " + color;
    }
  </script>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *