Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 501
Taylor Gomez Avatar asked Nov 03 '22 08:11

Taylor Gomez


1 Answers

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.

like image 135
acjay Avatar answered Nov 08 '22 05:11

acjay