Taylor Gomez
Taylor Gomez

Reputation: 330

Jquery get background gradient color

I want get background color and putting it in body, for example my background is as in class FirstColor:

.FirstColor{
    background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#ECAA63), to(#E36D0A));
}

Now i want get colors #ECAA63 and #E36D0A of background in class .FirstColor and replace they instead colors in body

body is as:

body{
    background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 350, from(#CEEEEE), to(#98BFF1));
}

Replace they of class .FirstColor to body as:

#ECAA63 - instead -> #CEEEEE
#E36D0A - instead -> #98BFF1

I tried to get background color ac: http://jsfiddle.net/rKQwu/ But can not done.

Upvotes: 5

Views: 3851

Answers (2)

Alnitak
Alnitak

Reputation: 339786

The CSS background style is a composite of several more-specific background-XXX attributes.

The -webkit-gradient is actually stored in the background-image attribute, and not in background-color as you had in your original code. It's also available, of course, in the compound background value.

You will need to parse that string, as shown in @acjohnson55's answer.

Note that in Chrome at least, the returned string outputs the colours in rgb(r, g, b) syntax and not as a hex string. You need to ensure that the colours you write back are also wrapped in rgb(...).

See http://jsfiddle.net/alnitak/xG4SW/, based on your latest fiddle.

Upvotes: 1

acjay
acjay

Reputation: 36511

First of all, why not just switch the classes of the divs instead of modifying the styles directly?

But if there's a reason you need to do it, then you need to parse the from and to values from the style value. As I said in my comment, your code seems to be fine in your jsfiddle; the problem appears to be that you selected MooTools instead of jQuery for your library, and after I switched that, it worked as expected. I don't know much about the Webkit standard, but on Chrome 23, the hex values are converted to rgb(r, g, b) style triplets, so I wrote a little code to parse those out:

var bgGrad = $('.FirstColor').css("background");
var parseRgb = (function (rgbStr) { return rgbStr.match(/rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)/); });
var fromStr = bgGrad.match(/from\((.*)\),/)[1];
var fromRgb = parseRgb(fromStr);

var toStr = bgGrad.match(/to\((.*)\)\)/)[1];
var toRgb = parseRgb(toStr);

alert('From rgb: ' + fromRgb.slice(1,4) + '\nTo rgb: ' + toRgb.slice(1, 4));
​

After this code (in the jsfiddle here), fromRgb and toRgb are arrays of 3 rgb values. It should be trivial to rebuild a new background gradient string once the values are extracted and modified as you see fit. I don't know enough to know how robust this code is to different cases, but it seems to work fine for me on the above Chrome version for the example you gave.

Upvotes: 1

Related Questions