RGB to Hex Color Converter With Javascript

In this article you will learn how to create RGB to Hex Color Convert using JavaScript. You can convert Hex Color To RGB using this javascript RGB to Hex Color Convert.

This kind of RGB to Hex Color Convert project will give you a lot of ideas about JavaScript. If you are a business person then you can try this type of project. 

Here I have given all the code and step by step explanation of this project (Convert RGB to HEX color in JavaScript).

RGB To HEX / Hex To RGB Converter in Javascript

The RGB to Hex color conversion is a process of converting RGB (Red, Green, Blue) color values to their equivalent hexadecimal representation. In web development, this conversion is often required when specifying colors in stylesheets or manipulating colors programmatically.

See the Pen Untitled by Shantanu Jana (@Shantanu-Jana-the-encoder) on CodePen.

This RGB to Hex Color Convert project has 2 input boxes. If you input the color code in any box, it will automatically change the color in the other field.

Step 1: RGB to Hex Color Convert - HTML

Now we need to create the structure of this JavaScript RGB to Hex Color converter using HTML code.

<div class="container">
    <!-- RGB input section -->
    <div class="wrapper">
        <label for="rgb">RGB</label>
        <input type="text" id="rgb" oninput="toHex()" placeholder="Enter RGB Value">
    </div>

    <!-- HEX input section -->
    <div class="wrapper">
        <label for="hex">HEX</label>
        <input type="text" id="hex" oninput="toRgb()" placeholder="Enter Hex Value">
    </div>
</div>

Step 2: RGB to Hex Convert - CSS

Now we need to design this RGB to Hex Color converter using CSS. For this I used very simple CSS.

/* Apply styles to all elements, resetting padding and margin */
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: "Poppins", sans-serif; /* Use the Poppins font or sans-serif as a fallback */
}

/* Apply styles to the entire body */
body {
    width: 100%; /* Occupy the full width of the viewport */
    background-color: #976efa; /* Set the background color of the body */
}

/* Styling for the main container */
.container {
    background-color: #ffffff; /* Set background color for the container */
    width: 80vmin; /* 80% of the viewport minimum dimension */
    min-width: 250px; /* Minimum width of the container */
    display: flex; /* Use flexbox for layout */
    flex-wrap: wrap; /* Allow items to wrap to the next line if needed */
    align-items: center; /* Align items vertically at the center */
    justify-content: center; /* Center items horizontally */
    gap: 50px; /* Set the gap between child elements */
    position: absolute; /* Position absolutely within the nearest positioned ancestor */
    transform: translate(-50%, -50%); /* Center the container using translate */
    top: 50%; /* Position the container at the vertical center */
    left: 50%; /* Position the container at the horizontal center */
    padding: 50px 10px; /* Padding for the container */
    border-radius: 5px; /* Apply border-radius for rounded corners */
}

/* Styling for the wrapper divs inside the container */
.wrapper {
    width: 230px; /* Set a specific width for the wrapper */
}

/* Styling for labels within the wrapper */
label {
    font-weight: 600; /* Set font weight for labels */
}

/* Styling for input fields within the wrapper */
input {
    width: 100%; /* Occupy the full width of the parent */
    padding: 5px 0; /* Add padding to the top and bottom of the input */
    outline: none; /* Remove default focus outline */
    border: none; /* Remove borders */
    border-bottom: 2px solid #404050; /* Add a bottom border with a specific color */
    font-size: 20px; /* Set font size for the input */
    font-weight: 400; /* Set font weight for the input */
    margin-top: 5px; /* Add margin to the top of the input */
}

Step 3: Hex To RGB Converter - JavaScript

Now it’s time to activate this project (How to Convert RGB to HEX in JavaScript) by JavaScript.

// Get references to the HTML input elements
let hexInput = document.getElementById("hex");
let rgbInput = document.getElementById("rgb");

// Execute when the window has loaded
window.onload = () => {
    // Reset input values on page load
    hexInput.value = "";
    rgbInput.value = "";
}

// Function to set valid state for an input element
function valid(element) {
    element.style.color = "#202040"; // Set text color for valid input
}

// Function to set invalid state for an input element and reset the other element's value
function invalid(element, otherElement) {
    element.style.color = "#f04624"; // Set text color for invalid input
    otherElement.value = 0; // Reset the value of the other element
}

// Function to convert Hex to RGB
function toRgb() {
    let hexCode = hexInput.value;
    let rgbArr = [];

    // Check if the Hex code is valid
    if (/^#?[A-Fa-f0-9]{6}$/.test(hexCode)) {
        valid(hexInput);
        hexCode = hexCode.split("#")[1] || hexCode;

        // Convert each pair of hex digits to decimal and push to the array
        for (let i = 0; i < hexCode.length; i += 2) {
            rgbArr.push(parseInt(hexCode[i] + hexCode[i + 1], 16));
        }

        // Log the RGB array to the console
        console.log(rgbArr);

        // Display the RGB value in the input and change the background color
        rgbInput.value = "rgb(" + rgbArr.join(", ") + ")";
        document.body.style.backgroundColor = "rgb(" + rgbArr.join(", ") + ")";
    } else {
        // Handle invalid Hex input
        invalid(hexInput, rgbInput);
    }
}

// Function to convert RGB to Hex
function toHex() {
    let rgbCode = rgbInput.value;

    // Regular expressions for valid RGB formats
    let rgbRegex1 = /^rgb\([0-9]{1,3},[0-9]{1,3},[0-9]{1,3}\)$/;
    let rgbRegex2 = /^[0-9]{1,3},[0-9]{1,3},[0-9]{1,3}$/;

    // Initial Hex code
    let hex = "#";

    // Check if the RGB code is valid
    if (rgbRegex1.test(rgbCode) || rgbRegex2.test(rgbCode)) {
        rgbCode = rgbCode.replace(/[rgb()]+/g, "") || rgbCode;
        rgbCode = rgbCode.split(",");

        // Check if all RGB values are within the valid range (0-255)
        let condition = rgbCode.every((value) => {
            return parseInt(value) <= 255;
        });

        if (condition) {
            // Handle valid RGB input
            valid(rgbInput);

            // Convert each RGB value to hexadecimal and concatenate
            rgbCode.forEach(value => {
                value = parseInt(value).toString(16);
                hex += value.length == 1 ? "0" + value : value;
            });

            // Set Hex input value and change the background color
            hexInput.value = hex;
            document.body.style.backgroundColor = hex;
        } else {
            // Handle invalid RGB input
            invalid(rgbInput, hexInput);
        }
    } else {
        // Handle invalid RGB input
        invalid(rgbInput, hexInput);
    }
}

Converting RGB to Hex is a common task in web development, and JavaScript provides a convenient way to achieve this. The algorithm presented in this article is a simple and effective solution for converting RGB values to their Hexadecimal representation.

Hope you liked this article. If you want to know something, you can comment me.

Leave a Comment

Home
Menu
Instagram
Search