RGB To HEX / Hex To RGB Converter Using Javascript

Summarize

Git is a distributed version control system DVCS designed for efficient source code management, suitable for both small and large projects. It allows multiple developers to work on a project simultaneously without overwriting changes, supporting collaborative work, continuous integration, and deployment. This Git and GitHub tutorial is designed for beginners to learn fundamentals and advanced concepts, including branching, pushing, merging conflicts, and essential Git commands. Prerequisites include familiarity with the command line interface CLI, a text editor, and basic programming concepts. Git was developed by Linus Torvalds for Linux kernel development and tracks changes, manages versions, and enables collaboration among developers. It provides a complete backup of project history in a repository. GitHub is a hosting service for Git repositories, facilitating project access, collaboration, and version control. The tutorial covers topics such as Git installation, repository creation, Git Bash usage, managing branches, resolving conflicts, and working with platforms like Bitbucket and GitHub. The text is a comprehensive guide to using Git and GitHub, covering a wide range of topics. It includes instructions on working directories, using submodules, writing good commit messages, deleting local repositories, and understanding Git workflows like Git Flow versus GitHub Flow. There are sections on packfiles, garbage collection, and the differences between concepts like HEAD, working tree, and index. Installation instructions for Git across various platforms Ubuntu, macOS, Windows, Raspberry Pi, Termux, etc. are provided, along with credential setup. The guide explains essential Git commands, their usage, and advanced topics like debugging, merging, rebasing, patch operations, hooks, subtree, filtering commit history, and handling merge conflicts. It also covers managing branches, syncing forks, searching errors, and differences between various Git operations e.g., push origin vs. push origin master, merging vs. rebasing. The text provides a comprehensive guide on using Git and GitHub. It covers creating repositories, adding code of conduct, forking and cloning projects, and adding various media files to a repository. The text explains how to push projects, handle authentication issues, solve common Git problems, and manage repositories. It discusses using different IDEs like VSCode, Android Studio, and PyCharm, for Git operations, including creating branches and pull requests. Additionally, it details deploying applications to platforms like Heroku and Firebase, publishing static websites on GitHub Pages, and collaborating on GitHub. Other topics include the use of Git with R and Eclipse, configuring OAuth apps, generating personal access tokens, and setting up GitLab repositories. The text covers various topics related to Git, GitHub, and other version control systems Key Pointers Git is a distributed version control system DVCS for source code management. Supports collaboration, continuous integration, and deployment. Suitable for both small and large projects. Developed by Linus Torvalds for Linux kernel development. Tracks changes, manages versions, and provides complete project history. GitHub is a hosting service for Git repositories. Tutorial covers Git and GitHub fundamentals and advanced concepts. Includes instructions on installation, repository creation, and Git Bash usage. Explains managing branches, resolving conflicts, and using platforms like Bitbucket and GitHub. Covers working directories, submodules, commit messages, and Git workflows. Details packfiles, garbage collection, and Git concepts HEAD, working tree, index. Provides Git installation instructions for various platforms. Explains essential Git commands and advanced topics debugging, merging, rebasing. Covers branch management, syncing forks, and differences between Git operations. Discusses using different IDEs for Git operations and deploying applications. Details using Git with R, Eclipse, and setting up GitLab repositories. Explains CI/CD processes and using GitHub Actions. Covers internal workings of Git and its decentralized model. Highlights differences between Git version control system and GitHub hosting platform.

2 trials left

Hello Everyone, In this tutorial we are going to create an RGB to HEX and HEX to RGB converter using Javascript. There are many rgb to hex converter tools using js are available but today let us make this tool ourselves with HTML, CSS and Vanilla Javascript. This is a great project for javascript intermediates. In this converter tool consists of two input fields. One for RGB and another one for Hex. If the user wants to convert his RGB colour code into HEX code, he needs to enter the colour value in the RGB field and the HEX equivalent will be displayed in the other field. Similarly, for Hex to RGB conversion the user has to enter the colour code in the HEX field and output will be displayed in the RGB field. So this is All in one RGB to HEX and HEX to RGB converter tool.

HTML

Copy - Paste the html code below into your HTML file. We start the HTML code by create a container div. Inside this container are two wrapper. Each of the wrappers encloses a label and an input field. The first label is for the RGB field while the second is for the HEX field.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RGB-Hex Converter | Codegyan</title>
    <!--Google Font-->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <!--Stylesheet-->
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="wrapper">
            <label for="rgb">RGB</label>
            <input type="text" id="rgb" oninput="toHex()" placeholder="Enter RGB Value">
        </div>
        <div class="wrapper">
            <label for="hex">HEX</label>
            <input type="text" id="hex" oninput="toRgb()" placeholder="Enter Hex Value">
        </div>
    </div>
    <!--Script-->
    <script src="script.js"></script>
</body>
</html>

CSS

Next, You have to paste the code provide below into the style.css file. We do a regular CSS reset by removing the default margins and paddings of all the elements. Next we add #976efa colour to the document body. After that we have add css for container div. We place and arrange the wrapper by using the flex layout. We use the flex-wrap property to make it responsive.

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: "Poppins",sans-serif;
}
body{
    width: 100%;
    background-color: #976efa;
}
.container{
    background-color: #ffffff;
    width: 80vmin;
    min-width: 250px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: 50px;
    position: absolute;
    transform: translate(-50%,-50%);
    top: 50%;
    left: 50%;
    padding: 50px 10px;
    border-radius: 5px;
}
.wrapper{
    width: 230px;
}
label{
    font-weight: 600;
}
input{
    width: 100%;
    padding: 5px 0;
    outline: none;
    border: none;
    border-bottom: 2px solid #404050;
    font-size: 20px;
    font-weight: 400;
    margin-top: 5px;
}

JavaScript

Lastly, we add functionality to this converter tool using javascript. You have to Copy Paste the code below into your script.js file. On window load, we clear both the input fields. When the user inputs something in the Hex field, the toRGB() is called. First the input from the input field is validated. If the input is invalid the invalid() is called.

Regular Expressions:

^#{0,1}: 0 or 1 # in the start(i.e # is optional). [A-Fa-f0-9]{6}$: 6 characters from A to F or a to f or any number till the end of the input. The user can either use the format with ‘#’ or no ‘#’ for the HEX Code. That is both ‘2345ac’ and ‘#2345ac’ are valid. The parseInt(value,16) would convert the hexadecimal input to number.

let hexInput = document.getElementById("hex");
let rgbInput = document.getElementById("rgb");

window.onload=()=>{
    hexInput.value = "";
    rgbInput.value = "";
}

function valid(element){
    element.style.color = "#202040";
}

function invalid(element,otherElement){
    element.style.color = "#f04624";
    otherElement.value = 0;
}

function toRgb(){
    let hexCode = hexInput.value;
    let rgbArr = [];
    if(/^#?[A-Fa-f0-9]{6}$/.test(hexCode)){
        valid(hexInput);
        hexCode = hexCode.split("#")[1] || hexCode;
        for(let i=0; i<hexCode.length;i+=2){
            rgbArr.push(parseInt(hexCode[i] + hexCode[i+1], 16));
            console.log(rgbArr);
        }
        rgbInput.value = "rgb(" + rgbArr + ")";
        document.body.style.backgroundColor = "rgb(" + rgbArr + ")";
    }
    else{
        invalid(hexInput,rgbInput);
    }
}

When the user enters the colour code in the RGB field, the toHex() is called. This function first validates the input code using the regular expressions.

Regular Expressions:

^rgb\(: Start with ‘rgb(‘. [0-9]{1,3},[0-9]{1,3},[0-9]{1,3}: Three values seperated by commas.Each value would be 1/2/3 digit. \)$: ends with ‘)’.

function toHex(){
    let rgbCode = rgbInput.value;
    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}$/
    let hex = "#";
    if(rgbRegex1.test(rgbCode) || rgbRegex2.test(rgbCode)){
        rgbCode = rgbCode.replace(/[rgb()]+/g,"") || rgbCode;
        rgbCode = rgbCode.split(",");
        let condition = rgbCode.every((value) => {
            return parseInt(value) <= 255;
        });
        if(condition){
            valid(rgbInput);
            rgbCode.forEach(value => {
                value = parseInt(value).toString(16);
                hex += value.length == 1? "0"+value : value;
            });
            hexInput.value = hex;
            document.body.style.backgroundColor = hex;
        }
        else{
            invalid(rgbInput,hexInput);
        }
    }
    else{
        invalid(rgbInput,hexInput);
    }

}
Also Read : How To Create Minion Eyes That Follows Mouse Cursor

If you wann to check the demo of this code, then you can check using below demo button.

Click on the following download button to download all source code files of converter tools directly on your computer.

Final Word

In this way, we can create rgb to hex converter tool using html, css & JavaScriptI hope you all like this tutorial. Keep with us for next tutorial. if you wann the source code of this code you can get this on our github account. If you have any query please free to contact us Or comment below.

You may also like this!