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.