Convert FireFox Color rgb(xxx,yyy,zzz) to Hex CodeUnit 26 MAY 2010

Firefox has a nasty habit of returning element background colors and colors in general in the format

rgb(xxx,yyy,zzz)

as opposed to the normal

#xxyyzz

hexadecimal format we’ve been accustomed to seeing from the likes of Internet Exlorer and the rest of its browser ilk.

Obviously this can trip up a fair bit of your otherwise nifty jQuery or plain old vanilla Javascript driven color features and as such, is definitely something that generally does have to be dealt with by your code.

Hence the following little useful Javascript function to use on any element color or background-color retrieval call:

//Helper function to convert a digit to a two column Hex representation
function toHex(N) {
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

//Function to convert rgb() format values into normal hex values
function RGBtoHEX(str)
{
	if (str.substring(0, 3) == 'rgb') {
		var arr = str.split(",");
		var r = arr[0].replace('rgb(','').trim(), g = arr[1].trim(), b = arr[2].replace(')','').trim();
		var hex = [
			toHex(r),
			toHex(g),
			toHex(b)
		];
		return "#" + hex.join('');				
	}
	else{
		return str;
	}
}

So slapping this into your code would result in you changing your calls to look like this:

alert(RGBtoHEX($('#myelement').css('color')));

As you can see by examining the inside of RGBtoHex, it will only attempt to change the values fed into it in the rgb(xxx,yyy,zzz) format. Values like the one returned by IE (i.e. #06a660) will be returned unharmed!

Nifty and useful in other words!

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.