How to convert RGB value to HEX in javascript

0 votes
27 views
asked May 27, 2016 by slape
HI All

   How to convert RGB value to HEX in javascript. Please provide the valid code for the conversion

Thanks in advance

1 Answer

0 votes
answered May 27, 2016 by admin (8,115 points)
Hi

  I have tried this code its working fine..

function convertRGBtoHEX (){
            if(red  <= 256 && green <= 256 && blue <= 256) {
               var colorValue =  "#".concat(((blue | green << 8 | red << 16) / 0x1000000).toString(16).substring(2));

                if(blue == 0 && colorValue.length <= 5){
                    colorValue = insert(colorValue,colorValue.length,"00");
                }
                if(red == 0 && colorValue.length <= 5){
                    colorValue = insert(colorValue,1,"00");
                }
                if(blue== 0 && colorValue.length <= 5){
                    colorValue = insert(colorValue,3,"00");
                }
            }
    };

function insert(str, index, value) {
        return str.substr(0, index) + value + str.substr(index);
    }
...