html5 - How can I change a CSS gradient via JavaScript? -
i have div following gradient applied it:
/* mozilla firefox */ background-image: -moz-linear-gradient(top, #2e2e28 0%, #4d4c48 100%); /* opera */ background-image: -o-linear-gradient(top, #2e2e28 0%, #4d4c48 100%); /* webkit (safari/chrome 10) */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #2e2e28), color-stop(1, #4d4c48)); /* webkit (chrome 11+) */ background-image: -webkit-linear-gradient(top, #2e2e28 0%, #4d4c48 100%); /* ie10+ */ background: -ms-linear-gradient(top, #2e2e28 0%,#4d4c48 100%); /* w3c */ background: linear-gradient(top, #2e2e28 0%,#4d4c48 100%);
how change "#2e2e28" number, still avoid cross-browser nightmare?
with jquery it'll :
$('.gradient').css({'background-image': 'linear-gradient(to top, #2e2e28 0%, #4d4c48 100%)'});
for safari :
$('.gradient').css({'background-image': '-webkit-linear-gradient(top, #2e2e28 0%, #4d4c48 100%)'});
see here live example.
seems work cross-browser.
edit :
i did small plugin can different colors :
;(function($) { var issafari = /safari/.test(navigator.useragent) && /apple computer/.test(navigator.vendor); var methods = { init: function (settings) { settings = $.extend( { 'colors' : ['red', 'blue'], 'direction' : 'top' }, settings); return this.each(function(){ if($.isarray(settings.colors) && settings.colors.length >= 2) { $(this).css({ 'background': methods.gradienttostring(settings.colors, settings.direction) }); } else { $.error('please pass array'); } }); }, gradienttostring: function (colors, direction) { var nbcolors = colors.length; //if no percent, need calculate them if(colors[0].percent === undefined) { //passed colors array make object if(colors[0].color === undefined) { var tmp = []; for(i=0; < nbcolors; i++) tmp.push({'color':colors[i]}); colors = tmp; } var p = 0, percent = 100 / (nbcolors - 1); //calculate percent for(i=0; i< nbcolors; i++) { p = === 0 ? p : (i == nbcolors-1 ? 100 : p + percent); colors[i].percent = p; } } var = issafari ? '' : 'to'; //build string var gradientstring = issafari ? '-webkit-linear-gradient(' : 'linear-gradient('; gradientstring += +' '+ direction; for(i=0; < nbcolors; i++) gradientstring += ', '+ colors[i].color + ' ' + colors[i].percent + '%'; gradientstring += ')'; return gradientstring; } }; $.fn.gradientgenerator = function () { return methods.init.apply( this, arguments ); }; })(jquery);
use example :
$('.gradient').gradientgenerator({ colors : ['#2e2e28', '#4d4c48'] }); $('.change-color').on('click', function(e) { e.preventdefault(); $('.gradient').gradientgenerator({ colors : [{color:'#4d4c48',percent:0}, {color:'#282827', percent:30}, {color:'#2e2e28', percent: 100}], direction : 'left' }); });
see working here.