jQuery Color Picker Plugin: Convert RGB to HEX CodeUnit 08 JUL 2010

I’ve written on the excellent jQuery Color Picker plugin from eyecon.ro before, but a question was recently raised on how to use its RGB output in code. Well actually it turns out that most browsers return its value as a standard HEX color value, but one browser in particular (and I’m not naming names here but it is the one who everyone who think themselves better than the average home user seems to love) returns the value as a RGB color string.


So how to deal with this then?

Well the solution is to run whatever is returned by the color picker on change through a RGB to HEX function, but a function that only fires when working on a RGB string and not a HEX string.

So lets have a look then:

//actual converter function called by main function

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 called to return hex string value
function RGBtoHEX(str)
	//check that string starts with 'rgb'
	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 = [
		return "#" + hex.join('');				
		//string not rgb so return original string unchanged		
    return str;

And there you go. Simply run all returned color values by the plugin through RGBtoHex() first, and you should be good to go with all your little DOM color style manipulations! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Anil D

    Thanks for such a nice piece of code, but its not working in IE for me, anything change required for IE?

  • Michael

    Where do you add your functions in? there is already a RGBtoHex defined in colorpicker.js. is your code supposed to go overtop of this section or be called from its own file after the colorpicker has returned the value?


    • oh, in the your main code body. this is purely an extra function to deal with firefox’s preference for returning color strings in the RGB format instead of the usual, expected HEX string format.