views:

6214

answers:

6

I'm kind of new to JavaScript and jQuery and now I'm facing a problem:

I need to post some data to PHP and one bit of the data needs to be the background color hex of div X.

jQuery has the css("background-color") function and with it I can get RGB value of the background into a JavaScript variable.

The CSS function seems to return a string like this rgb(0, 70, 255).

I couldn't find any way to get hex of the background-color (even though it's set as hex in CSS).

So it seems like I need to convert it. I found a function for converting RGB to hex, but it needs to be called with three different variables, r, g and b. So I would need to parse the string rgb(x,xx,xxx) into var r=x; var g=xx; var b=xxx; somehow.

I tried to google parsing strings with JavaScript, but I didn't really understand the regular expressions thing.

Is there a way to get the background-color of div as hex, or can the string be converted into 3 different variables?

+5  A: 

You can set a CSS color using rgb also, such as this:

background-color: rgb(0, 70, 255);

It is valid CSS, don't worry.


Edit: See nickf answer for a nice way to convert it if you absolutely need to.

lpfavreau
+1 - *if* the color has to be restored on some web page later on, then why do any work converting at all :)
Anurag
+17  A: 

try this out:

var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.

var parts = rgbString
        .match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
;
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

delete (parts[0]);
for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
var hexString = parts.join(''); // "0070ff"
nickf
+1 nice implementation with the the regex match, although I wonder if there's a constant space after the comma across all browsers
lpfavreau
Well, this is the actual answer, thanks. However for me Ipfavreau's answer worked, since I'm just posting the background-color to create a css file with php.
Ezdaroth
Wouldn't parts be ["rgb(0, 70, 255)","0","70","255"]?
Matthew Crumley
oh oops - i'll fix now
nickf
I love StackOverflow. Thanks, didn't want to figure this out myself. :-P
KyleFarris
great piece of code
monkeylee
+2  A: 

I found another function awhile back (by R0bb13). It doesn't have the regex, so I had to borrow it from nickf to make it work properly. I'm only posting it because it's an interesting method that doesn't use an if statement or a loop to give you a result. Also this script returns the hex value with a # (It was needed by the Farbtastic plugin I was using at the time)

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

// call the function: rgb( "rgb(0, 70, 255)" );
// returns: #0046ff

Note: The hex result from nickf's script should be 0046ff and not 0070ff, but no big deal :P

Update, another better alternative method:

function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return ("0" + parseInt(x).toString(16)).slice(-2);
 }
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
fudgey
@fudgey: I would rather move function hex(x) out of the scope of fucntion rgb2hex for performance improvement. Anyway it's a nice clean solution, thanks for sharing. Have a look at mine below, I would like your opinion.
Marco Demajo
A: 

I found this solution http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx and i am using it in my project

Amr ElGarhy
The solution provided at the link is WRONG because converts "rgb(0, 0, 0)" into "#0" instead of "#000000", the reason is that the << operator does not shift bits if the value to shift is a zero.
Marco Demajo
A: 

These solutions will fail in Chrome, as it returns an rgba(x,x,x,x) for background-color.

EDIT: This is not necessarily true. Chrome will still set backgrounds using rgb(), depending on what you are doing. Most likely as long as there is no alpha channel applied, Chrome will respond with rgb instead of rgba.

Kevin.Riggen
A: 

How about this solution, function stringRGB2HEX returns a copy of the input string where all occurencies of colors in the format "rgb(r,g,b)" have been replaced by the hex format "#rrggbb".

   //function for private usage of the function below
   //(declaring this one in global scope should make it faster rather than 
   //declaraing it as temporary function inside stringRGB2HEX that need to be
   //instantieted at every call of stringRGB2HEX
   function _rgb2hex(rgb_string, r, g, b) 
   {
      //VERY IMPORTANT: by adding (1 << 24) we avoid 'rgb(0, 0, 0)' to be mistakenly converted into '#0'
      var rgb = (1 << 24) | (parseInt(r) << 16) | (parseInt(g) << 8) | parseInt(b); //same thing of: ( r + (256 * g) + (65536 * b) + 16777216)
      //toString(16) specify hex 16 radix, works only for numbers [source: http://msdn.microsoft.com/en-us/library/dwab3ed2(v=VS.85).aspx]   
      return '#' + rgb.toString(16).substr(1); //substr(1) because we have to remove the (1 << 24) added above
   }

   function stringRGB2HEX(string)
   {
      if(typeof string === 'string')
         string = string.replace(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/g, _rgb2hex);
      return string;
   }

This one converts also rgb colors in complex styles like background.

A style.background value like: "none no-repeat scroll rgb(0, 0, 0)" is easily converted into "none no-repeat scroll #000000" by simply doing stringRGB2HEX(style.background)

Marco Demajo