views:

99

answers:

5

What would be the easiest way to transform

$('#my_element').css('backgroundColor')

to object like this:

{ r: red_value, g: green_value, b: blue_value, a: alpha_value }

?

+1  A: 

Say you have the following CSS rule:

#my_element {
    background-color: rgba(100, 0, 255, 0.5);
}

Then this is how you could get an RBGA object:

var colorStr = $('#my_element').css('backgroundColor'); // "rgba(100, 0, 255, 0.5)"

// using string methods
colorStr = colorStr.slice(colorStr.indexOf('(') + 1, colorStr.indexOf(')')); // "100, 0, 255, 0.5"
var colorArr = colorStr.split(','),
    i = colorArr.length;

while (i--)
{
    colorArr[i] = parseInt(colorArr[i], 10);
}

var colorObj = {
    r: colorArr[0],
    g: colorArr[1],
    b: colorArr[2],
    a: colorArr[3]
}
Matt Ball
A: 

Your first line will return something like rgb(xxx,xxx,xxx) by default and you can just parse it.

Simplier solution would be https://www.adaptavist.com/display/jQuery/Colour+Library

Māris Kiseļovs
A: 

http://www.javascripter.net/faq/hextorgb.htm

This script basically takes each color pair from your hexcolor code (for example #F0556A) and switches it to a integer using parseInt with base 16 .

Rakward
+2  A: 

You would do something like:

$.fn.ToRgb = function()
{
    if(this.charAt(0) == "#"){this = this.substring(1,7);} //remove the #
    return {
        R : parseInt(this.substring(0,2) ,16),
        G : parseInt(this.substring(2,4) ,16),
        B : parseInt(this.substring(4,6) ,16),
    }
}

RGB = $('#my_element').css('backgroundColor').ToRgb();


/*
   * console.log(rgb) =>
   * {
   *   R: X
   *   G: X
   *   B: X 
   * }
*/

Pretty simple :)

RobertPitt
I see that `$('#my_element').css('backgroundColor')` always returns something like `rgb(123, 87, 92)` or `rgba(123, 87, 92, 0.7)`. Can it return also things like `#123456` or `123456` ?
Misha Moroshko
This was not specifically asked for
RobertPitt
@Robert - it was implied that the input would be something like `rgba(...)` since a simple hex value like `#6400FF` cannot express opacity.
Matt Ball
very true. My bad.
RobertPitt
Which browser does this work in out of interest? I always forget which ones return things of the form "rgb(a,b,c)" and what might return other forms...
Chris
this should be cross-browser friendly.
RobertPitt
+2  A: 
var c = $('body').css('background-color');
var rgb = c.replace(/^(rgb|rgba)\(/,'').replace(/\)$/,'').replace(/\s/g,'').split(',');

for(var i in rgb) {
  console.log(rgb[i]);
}

Try it here http://jsbin.com/uhawa4

Edit :

var c = $('body').css('background-color');
var rgb = c.replace(/^rgba?\(|\s+|\)$/g,'').split(',');

for(var i in rgb) {
  console.log(rgb[i]);
}

or even simpler way, just aiming at numbers

var c = 'rgba(60,4,2,6)';
var rgb = c.match(/\d+/g);

for(var i in rgb) {
  console.log(rgb[i]);
}
Ninja Dude
Thanks ! This is pretty close to what I was looking for :)
Misha Moroshko