Random Color Generator

Random Color Generator

The best way to learn to program is to practice more and build projects. This is a small guide to create a random color generator for yourself. This article will cover how to generate random colors for your projects.

Key Concepts covered :

  • Math.random() and Math.floor()
  • Event Listeners
  • substring() and toString()

This is what we are going to build

Desktop View

image.png

We'll start with defining the UI for our project. We are going to use Bootstrap in this project. You can read more about Bootstrap in the official documentation of Bootstrap.

Create three files named - index.html, app.js, and styles.css

In our HTML file, we'll add the following links to load the bootstrap and also link the external stylesheet :

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<!-- Bootstrap JS-->
<script src="<https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js>" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles.css" />

Starter Template - index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <!-- Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css"
      integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU"
      crossorigin="anonymous"
    />
    <!-- Bootstrap JS-->
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js"
      integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/"
      crossorigin="anonymous"
    ></script>

    <title>Random Color Generator</title>
  </head>
  <body>
    <h1>Random Color Generator</h1>
    <script src="app.js"></script>
  </body>
</html>

Then we’ll replace the code inside the body tag with the following code in the index.html file :

 <div class="container text-center">
      <h1>Random Color Generator</h1>
      <!-- Color Card -->
      <div>
        <div class="color-card" id="colorCard"></div>
      </div>
      <!-- Random Color Generator Button-->
      <button
        type="button"
        id="randomColorGenerator"
        class="btn btn-dark"
        style="margin: 10px"
      >
        Generate Random Color
      </button>
      <!-- Color Codes -->
      <div class="row">
        <div class="col-sm">HEX Color Code</div>
        <div class="col-sm">
          <input id="colorCode" readonly="readonly" />
        </div>
      </div>
    </div>

styles.css

In the styles.css, place this code for styling the color card to display the color generated.

#colorCard {
    display: flex;
    height: 200px;
    width: 200px;
    border-radius: 20px;
    align-items: center;
    justify-content: center;
    margin: auto;
}
#colorCode {
    border: 1px solid #979090;
    padding: 10px;
    border-radius: 5px;
    width: 50%;
}

Now we’ll work on our actual logic behind the random color generator: First, we’ll create a constant to store the DOM elements so that we can handle them further.

const colorCard = document.getElementById('colorCard'); 
const randomColorGenerator = document.getElementById('randomColorGenerator');
const colorCode = document.getElementById('colorCode');

The basic idea behind the random color generator is to find a random color code between and #000000 (black) and #ffffff (white). To implement this logic we are going to calculate the random code using the following logic:

let randomColor = Math.floor(Math.random()*16777215).toString(16)

let randomColor - The random color code will be stored in this variable. (Math.random()*16777215) - The Math.random() function is used to find a random number between 0 and 1.

The number of colors that exist from black to white as per RGB values are 16777216, so converting 16777216 into hexadecimal gives us code greater than ffffff therefore 16777215 will be used as the highest range for the conversion.

Math.random() will give us - 0.5830347221497629 and Math.random()*16777215 will give us - 9781698.885971835

Math.floor() - Returns the greatest integer less than or equal to its numeric argument. Here, it will round off the value of Math.floor(Math.random()*16777215) And it will give us - 9781698

toString(16) - This function returns the string value for the numeric values of the specific radix. Math.floor(Math.random()*16777215).toString(16) will give us - "9541c2"

Note - “9541c2” is the hexadecimal code generated. We have to append # in front of this code to get the color in our DOM.

Finalizing the App

app.js

const colorCard = document.getElementById("colorCard");
const randomColorGenerator = document.getElementById("randomColorGenerator");
const colorCode = document.getElementById("colorCode");

document.addEventListener("DOMContentLoaded", () => {
  let randomColor = Math.floor(Math.random() * 16777215).toString(16);
  colorCard.style.backgroundColor = `#${randomColor}`;
  colorCode.value = `#${randomColor}`;
});

randomColorGenerator.addEventListener("click", () => {
  let randomColor = Math.floor(Math.random() * 16777215).toString(16);
  colorCard.style.backgroundColor = `#${randomColor}`;
  colorCode.value = `#${randomColor}`;
});

const CopyToClipboard = (id) => navigator.clipboard.writeText(id);

//to copy hex code
colorCode.addEventListener("click", () => {
  CopyToClipboard(colorCode.value);
  alert(`Copied : ${colorCode.value}`);
});

You now have an application for generating the random color and their HEX and RGB Code. You can get the full code for this project here.

I hope you found the article interesting and helpful. Please do not hesitate to provide feedback. Have an amazing day! 🎉✨