RGB Color Generator with JavaScript

Do you want to create RGB Color Generator using javascript? In this article I will help you completely to create RGB Color Generator using html css and javascript.

RGB color generators are powerful tools that enable developers to generate a vast array of colors dynamically, providing a visually appealing experience on websites and applications. 

In this article, we’ll explore how to build a simple RGB color generator using JavaScript, HTML, and CSS.

JavaScript RGB Color Generator

The JavaScript RGB Color Generator typically works by generating random values for the red, green, and blue components and then using these values to create an RGB color string. 

This string can be applied to HTML elements, such as divs or backgrounds, to dynamically change their color. Each component can have values ranging from 0 to 255, allowing for a wide spectrum of colors.

See the Pen Untitled by Growthpanda (@Growthpanda) on CodePen.

This RGB Color Generator has 3 slides to select red, green and blue colors. Then below I have created a display in which RGB Color can be generated. There is a copy button that lets you copy colors.

RGB Color Generator HTML Code

To begin, let’s set up the basic HTML structure for our RGB color generator. Here we first created an area and created 3 input sliders. Then I created another result input and copy button.

<div class="container">
      <div class="wrapper">
        <label for="red">R</label>
        <input type="range" min="0" max="255" value="0" id="red" />
      </div>
      <div class="wrapper">
        <label for="green">G</label>
        <input type="range" min="0" max="255" value="0" id="green" />
      </div>
      <div class="wrapper">
        <label for="blue">B</label>
        <input type="range" min="0" max="255" value="0" id="blue" />
      </div>
      <div class="result">
        <input type="text" value="rgb(0,0,0)" readonly />
        <button id="copy-btn">Copy Color Code</button>
      </div>
    </div>

RGB Color Slider CSS Code

Next, let’s add some basic styling to make our color generator visually appealing. Create a file named styles.css and add the following styles.

CSS has no role to generate colors here. This css is provided only to design the RGB Color Slider.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
.container {
  background-color: #ffffff;
  width: min(90%, 31.25em);
  padding: 4em 2em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  color: #142b37;
  font-weight: 600;
  border-radius: 0.5em;
  display: grid;
  justify-content: center;
  box-shadow: 0 2em 3em rgba(0, 0, 0, 0.2);
}
.wrapper {
  width: 100%;
  display: flex;
  align-items: space-between;
  gap: 1em;
  margin-bottom: 2.2em;
}

label {
  font-size: 1.8em;
}
input[type="range"] {
  width: 100%;
}
.result {
  width: 100%;
  display: grid;
  grid-template-columns: 7fr 5fr;
  gap: 1em;
}
input[type="text"],
button {
  font-size: 1em;
  border-radius: 0.5em;
  border: none;
  outline: none;
}
input[type="text"] {
  background-color: #ebeaea;
  padding: 1.2em 0.5em;
  font-weight: 400;
}
input[type="text"]::selection {
  background-color: transparent;
}
button {
  background-color: #0075ff;
  color: #ffffff;
  font-weight: 600;
  cursor: pointer;
}

RGB Color Generator JavaScript Code

Now, let’s add the functionality to our RGB color generator. Create a file named script.js and add the following JavaScript code. Here below code for RGB Color Generator is most important. I have given some explanation here which will help you.

// Selecting elements from the DOM
const result = document.querySelector(".result input");
const copyBtn = document.getElementById("copy-btn");
const sliders = document.querySelectorAll(".wrapper input[type='range']");
const rColor = document.getElementById("red");
const gColor = document.getElementById("green");
const bColor = document.getElementById("blue");

// Function to generate a color based on slider values
let generateColor = () => {
  let rColorValue = rColor.value;
  let gColorValue = gColor.value;
  let bColorValue = bColor.value;

  // Create an RGB color string
  let finalColor = `rgb(${rColorValue}, ${gColorValue}, ${bColorValue})`;

  // Update the input field and the background color of the body
  result.value = finalColor;
  document.body.style.backgroundColor = finalColor;
};

// Function to copy the color code to the clipboard
let copyColorCode = () => {
  // Select the text in the result input field
  result.select();
  // Execute the copy command
  document.execCommand("copy");
  
  // Update the copy button text and revert it after a short delay
  copyBtn.innerText = "Copied!";
  setTimeout(() => {
    copyBtn.innerText = "Copy Color Code";
  }, 1000);
};

// Event listeners for input changes, initial color generation, and copy button click
sliders.forEach((inp) => {
  inp.addEventListener("input", generateColor);
});
window.addEventListener("load", generateColor);
copyBtn.addEventListener("click", copyColorCode);

Creating an RGB color generator with JavaScript adds a dynamic and interactive element to your web projects. This simple example can be expanded upon by adding features such as color codes display, color history, or even integrating it into a larger design project.

Hopefully you have learned from this article How To Make RGB Color Generator Using JavaScript. I have shared many more projects using JavaScript before you can check them out.

Creating an RGB color slider with JavaScript involves using HTML for the structure, CSS for styling, and JavaScript for handling user interactions. Here’s a simple example of how you can create RGB color sliders:

<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}

.color-box {
width: 200px;
height: 200px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

input[type=”range”] {
width: 100%;
margin: 10px 0;
}
</style>
<div>
<div class=”color-box” id=”color-box”></div>
<input type=”range” id=”red-slider” min=”0″ max=”255″ value=”0″>
<input type=”range” id=”green-slider” min=”0″ max=”255″ value=”0″>
<input type=”range” id=”blue-slider” min=”0″ max=”255″ value=”0″>
</div>
<script>
// Function to update the color based on slider values
function updateColor() {
const red = document.getElementById(‘red-slider’).value;
const green = document.getElementById(‘green-slider’).value;
const blue = document.getElementById(‘blue-slider’).value;

const colorBox = document.getElementById(‘color-box’);
colorBox.style.backgroundColor = `rgb(${red}, ${green}, ${blue})`;
}

// Add event listeners to sliders
document.getElementById(‘red-slider’).addEventListener(‘input’, updateColor);
document.getElementById(‘green-slider’).addEventListener(‘input’, updateColor);
document.getElementById(‘blue-slider’).addEventListener(‘input’, updateColor);

// Initial color update
updateColor();
</script>

To generate a random color in JavaScript, you can use the following code snippet. This example generates a random RGB color:

// Function to generate a random RGB color
function generateRandomColor() {
const red = Math.floor(Math.random() * 256);
const green = Math.floor(Math.random() * 256);
const blue = Math.floor(Math.random() * 256);

// Return the RGB color as a string
return `rgb(${red}, ${green}, ${blue})`;
}

// Example usage:
const randomColor = generateRandomColor();
console.log(randomColor);

To generate random color hex codes with JavaScript, you can use the following code. This example generates a random hex color code each time the generateRandomColor function is called:

// Function to generate a random hex color code
function generateRandomColor() {
// Generate random values for red, green, and blue components
const randomColor = Math.floor(Math.random()*16777215).toString(16);

// Ensure the generated hex code has six digits
return “#” + “0”.repeat(6 – randomColor.length) + randomColor;
}

// Example usage:
const randomColorCode = generateRandomColor();
console.log(randomColorCode);

Leave a Comment

Home
Menu
Instagram
Search