RGB to Hex Color Converter - Javascript

Another javascript color converter I wrote on my phone while sick in bed. This script converts RGB color values to a CSS-formatted Hex string. Demo and source code with comments are below.

You can also check out the Hex-to-RGB Conversion Tool.


RGB-to-Hex Conversion

Formatted Hex Color Value:  


Again, this is old news, but hey I had nothing better to do :P It DOES provide useful feedback and IMHO is a little bit more robust than some of the other online tools:


//Function to convert RGB to Hex
function convert(rgbElement) { //takes container element id as argument
    var hex = []; //initialize hex variable
    var rgbForm = document.getElementById(rgbElement);
    var rgbInputs = rgbForm.getElementsByTagName('input'); //selects inputs
    var rgbValues = [];
    for (i = 0; i < 3; i++) { //limit to first 3 input elements
        if (rgbInputs[i].getAttribute('type') == 'text') { //only operate on text inputs
            rgbValues[i] = rgbInputs[i].value.replace(/([\D])*/g,''); //populate array values, strip non-digits
        }
    }
    var isValid = function (x) { //validate
        return (x.length === 3 && parseInt(x) !== NaN && parseInt(x) >= 0 && parseInt(x) <= 255);
    }
    for (i = 0; i < 3; i++) {
        //proceed only if every value is valid
        if (!isValid(rgbValues[i])) {
            alert("Please enter valid RGB values"); //Provide useful feedback if one of the values is invalid
            return "The RGB value " + rgbValues[i] + " is messin' me up :(";
        }
        var y = parseInt(rgbValues[i]),
            h1 = Math.floor(y / 16), //Use Math and modulus to get two integers...
            h2 = y % 16,
            hexChar = "0123456789abcdef"; //...which can be used as character indices of a string that contains all the valid Hex characters. We only have to define the Hex characters once.
        hex[i] = hexChar[h1] + hexChar[h2]; //Combine the 2 characters
    }
    hex = hex.join(''); //get rid of commas
    return "#" + hex; //return CSS-formatted hex string
}

You pass in the id of the container that wraps the input elements, in the “formid” property of a config object, and only the first three input elements will be used. If the input elements aren’t of type “text”, they won’t be used, returning an error. Open to suggestions on how to make this work better across different markup scenarios (please comment below).

Also see the Hex-to-RGB Color Converter here.