0

I trying to compare the styles of elements on my page. But one element dynamically changes it's text color to red, but represented as a rgb value. And the other element (to compare it with) uses #123456 values. Is there a converter somewhere that can take rgb and turn it into #number?

For example:

#000 instead of rgb(0, 0, 0)

4
  • Sorry I mean #number not what that was. Commented Sep 30, 2011 at 0:37
  • OP probably means rgb(#, #, #) vs. 0xRRGGBB Commented Sep 30, 2011 at 0:37
  • 3
    javascripter.net/faq/rgbtohex.htm Commented Sep 30, 2011 at 0:37
  • 1
    can you show your expected inputs/outputs? Commented Sep 30, 2011 at 0:37

2 Answers 2

3

People always forget that rgb colors can be expressed as percentages, as well as integers.

function rgbToHex(rgb){
    var i= 0, c, hex= '#',
    rgb= String(rgb).match(/\d+(\.\d+)?%?/g);
    while(i<3){
        c= rgb[i++];
        if(c.indexOf('%')!= -1){
            c= Math.round(parseFloat(c)*2.55);
        }
        c= (+c).toString(16);
        if(c.length== 1) c= '0'+c;
        hex+= c;
    }
    return hex;
}




alert(rgbtohex('rgb(255,127,0)')+'\n'+
rgbtohex('rgb(100%,50%,0)'));

/*  returned value: 
#ff7f00
#ff7f00
*/

// also works with arrays- rgbToHex([100,200,60])

// returned value: #64c83c

Sign up to request clarification or add additional context in comments.

Comments

2
function rgbToHex(R, G, B){
    return toHex(R) + toHex(G) + toHex(B);
}

function toHex(n){
    n = parseInt(n, 10);
    if( isNaN(n) ){ 
        return "00";
    }
    n = Math.max(0, Math.min(n,255));
    return "0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16);
}

edited. courtesy of http://www.javascripter.net/faq/rgbtohex.htm

2 Comments

Ah beat me to it! ;) The only thing i would suggest is to change your parseInt()s to parseInt("number string", 10) just to be safe.
I got an error. alert(colorToHex('rgb(0, 0, 0)')); returns #0 and that's it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.