How to Make a Random Color Generator in JavaScript

0

Hey guys today we are going to learn how to make a Random Color Generator in JavaScript. When you create a project using HTML CSS and JavaScript can be a fun and useful exercise for web developers. Whether you want to add a splash of color to your website or generate random colors for data visualization, this tutorial will guide you through the process. We’ll discuss the concept, steps, and important considerations without providing specific code.

Random Color Generator in JavaScript

Before we start coding, it’s essential to understand the RGB (Red, Green, Blue) color model or hex modal such as #6495ED. In this model, colors are represented as combinations of these three primary colors. Each color component is usually represented as an integer value between 0 and 6, where 0 with a hash sign.

To create a random color generator, we need to generate random values for the hex color codes. The resulting combination will create a unique color.

How to Make a Random Color Generator in JavaScript

I know you need a code for the project, but I made a video tutorial to learn How to make a Random Color Generator in JavaScript from scratch. You can watch it and learn all of the logic from scratch practically.

I hope you’ve watched the complete video, and learned something new from this tutorial. If you face any problems inside the tutorial, you can check out the source codes below.

You May Also Like:

Generate Random Hex Color using HTML CSS and JavaScript

Start by creating an HTML file that includes a button or any trigger for generating random colors. Link this HTML file to your JavaScript file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="css/style.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    />
    <script defer src="js/script.js"></script>
    <title>Random Color Generator using HTML CSS & JS</title>
  </head>
  <body>
    <div class="color_wrapper">
      <ul>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
        <li>
          <div class="color_box"></div>
          <span class="color_value">#eda004</span>
        </li>
      </ul>
      <button type="button">Generate Palate</button>
      <div class="message">You've Copied #eda004</div>
    </div>
  </body>
</html>

Once you use HTML codes, then you need to use CSS to design the page, you can find the CSS Codes below.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&family=Ruda:wght@400;600;700&display=swap");

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  background-color: #ddd;
  font-family: "poppins", sans-serif;
  overflow-x: hidden;
}

.color_wrapper {
  width: 100%;
  margin: 3rem 0;
}

.color_wrapper ul {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  margin: 2rem;
}

.color_wrapper ul li {
  list-style-type: none;
  padding: 5px;
  background-color: #fff;
  margin: 0.5rem;
  border-radius: 5px;
  transition: all 0.3s ease-in;
}

.color_wrapper ul li:hover {
  transform: translateY(-10px);
}

.color_wrapper .color_box {
  width: 170px;
  height: 170px;
  background-color: blueviolet;
  cursor: pointer;
  margin: 0.5rem;
}

.color_wrapper .color_value {
  text-align: center;
  display: block;
  font-size: 1.1rem;
}

button {
  display: block;
  margin: 0 auto;
  cursor: pointer;
  outline: none;
  border: none;
  color: #fff;
  font-family: inherit;
  padding: 1rem 4rem;
  border-radius: 5px;
  font-size: 1.1rem;
  background-color: #6495ed;
}

button:active {
  transform: scale(0.95);
}

.message {
  background-color: #6495ed;
  width: 250px;
  text-align: center;
  position: absolute;
  bottom: 0;
  right: 0;
  color: #fff;
  margin: 2rem 0;
  padding: 0.5rem;
  border-radius: 2px;
  transform: translateX(300%);
  transition: all 0.3s ease-in-out;
}

.message.active {
  transform: translateX(0%);
}

Use JavaScript’s built-in functions for generating random numbers, like Math.random(). Ensure that you scale and round the values to fit within the 0-6 range.

"use strict";

const btnEl = document.querySelector("button");
const ContainerEl = document.querySelector(".color_wrapper ul");
const messageEl = document.querySelector(".message");

// generate random color
const GenerateColors = () => {
  ContainerEl.innerHTML = "";

  // generate random color
  for (let i = 0; i < 24; i++) {
    let randomColor = Math.floor(Math.random() * 0xffffff).toString(16);
    randomColor = `#${randomColor.padStart(6, "0")}`;

    let html = ` <li>
                  <div class="color_box" style="background: ${randomColor}"></div>
                  <span class="color_value">${randomColor}</span>
                </li>`;

    ContainerEl.insertAdjacentHTML("afterbegin", html);

    // get the value
    const colorsliEl = document.querySelector(".color_wrapper ul li");

    colorsliEl.addEventListener("click", () => {
      copyColorCode(randomColor);
    });
  }
};

// copy color codes
const copyColorCode = (val) => {
  navigator.clipboard.writeText(val).then(() => {
    messageEl.textContent = `You've Copied ${val}`;
    messageEl.classList.add("active");

    setTimeout(() => {
      messageEl.classList.remove("active");
    }, 1500);
  });
};

GenerateColors();

// generate random color codes
btnEl.addEventListener("click", GenerateColors);

That’s it for random color generator in JavaScript. You can apply the generated color to a specific HTML element, like a background color, text color, border color, etc. JavaScript allows you to manipulate the CSS properties of HTML elements.

To make the color generation interactive, you can associate the color generation process with a button click or any other event. This way, users can trigger the generation as needed.

Ensure that the generated color is visually pleasing by considering brightness and contrast. You can use algorithms to adjust the brightness or ensure that the text color is legible against the background.

If you want to use the generated color elsewhere in your application, consider storing it in a variable to maintain consistency. Implement error handling to account for any unexpected values or issues that may occur during the generation process.

Conclusion:

Creating a random color generator in JavaScript is a fun and creative way to add visual appeal to your web applications. By following the steps and considering the important considerations mentioned in this tutorial, you can generate vibrant and engaging colors for various purposes. Feel free to incorporate this feature into your web projects and experiment with different variations to achieve the desired results.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.