Get RGB color code from HEX color code

This Javascript program generate the RGB color code of given HEX color code. Code is simple and understandable. Copy and paste in note pad and save as filename.html and then run. Enter hex code in textbox and click the button.


Below is the code:-


<html>

<head>

<title>Hex To Decimal</title>
<script type="text/javascript" language="javascript">
function addSeprators(ctrl)
{
   if(ctrl.value.length == 2)
   {
        ctrl.value = ctrl.value + "-";
   }
   
   if(ctrl.value.length == 5)
   {
        ctrl.value = ctrl.value + "-"; 
   }
   
   return ctrl.value;
}


function getRGBCode()
{


    var hexVal = document.getElementById('hex').value.toUpperCase();   
    var hexArr = new Array();
    var rgbVal = "";


      hexArr = hexVal.split('-');
      rgbVal = parseInt(hexArr[0],16) +"-"+ parseInt(hexArr[1],16) +"-"+ parseInt(hexArr[2],16); // parseInt(val, 16) returns decimal value of hex code.
    document.getElementById('colorDiv').style.background = "#"+hexArr[0]+hexArr[1]+hexArr[2];
    alert("Hex color code : " +hexVal+"\n\rRGB color code : " +rgbVal);
    
}


</script>
</head>

<body>

</body>
Enter Hex color code : 
<input type="text" name="hex" id="hex" maxlength="8" style="text-transform:uppercase;" onkeyup="return addSeprators(this);"/>
<input type="button" value="Hex To Dec" onclick="getRGBCode();" />
<div id="colorDiv" style="width:100px; height:25px;"></div>
</html>

Demo :-

http://www.navvtech.com/demo/colors/h2d.html

Comments

Post a Comment

Popular posts from this blog

Get Query String Values With Javascript

Change Css Class of li in ul onclick

Change Text Color with Javascript