javascript - Apply gradient or solid color on dynamic element -
i'm trying apply gradient or solid color element jquery. why jquery? because site has several different color combo's generating css classes work.
let's have list generated json call
<div class="colours"> <ul> <li class="black white"></li> <li class="green"></li> </ul> </div>
as can see need 1 list element gradient (black/white) , 1 solid (green) element.
so question how set either gradient when list class has 2 colors in or solid color when 1 color needed??
with code below gives me "producthtml not function" or [object object]
when try apply colors.
$.each(data.product.custom, function(i, custom) { var productshtml = []; $.each(custom.values, function(index, value){ var color = (value.title).tolowercase(); var colorclean = color.replace(/\s?\/\s?/," "); var colors = colorclean.split(/\s+/); if (colors.length===1) { colors[1] = colors[0]; } // var producthtml = '' + // '<li class="'+colorclean+'" ></li>'; var producthtml = $('<li></li>').css({ 'background': '-moz-linear-gradient(-45deg, + colors[0] + 0%, + colors[0] + 49%, + colors[1] + 49%, + colors[1] + 100%)', //etc etc }); productshtml.push(producthtml); }); productshtml = productshtml.join(''); $('.product.'+id+' .colours').html('<ul>'+productshtml+'</ul>'); });
what i'm doing wrong?
here solution using data-attribute.
- first iterate on <li> elements in .colours.
- then find data-colour attribute.
- create string necessary linear-gradient info.
- adding all colours (separated ",") in data attribute.
- closing linear-gradient info string.
- applying linear-gradient css rule
css()
.
note can have colour value:
data-colour("rgb(255,123,43)");
data-colour("#222 #546");
data-colour("rgb(2,150,255) #3a1");
$(".colours").find('li').each(function(index, e) { var $elem = $(e); var colourattri = $(this).data("colour"); var colours = colourattri.split(","); if (colours.length >= 2) { var linear = "linear-gradient(90deg, "; (var index in colours) { linear += colours[index]; if (index != colours.length - 1) { linear += ", "; } } linear += ")"; $elem.css({ background: linear, }); } else if (colours.length == 1) { $elem.css("background-color", colours[0]); } });
li { padding: 20px; color: white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="colours"> <ul> <li data-colour="black">some text here</li> <li data-colour="black, white">some text here</li> <li data-colour="red, blue">some text here</li> <li data-colour="pink, white">some text here</li> <!-- can take lot of colours--> <li data-colour="red, orange, green, blue, indigo, violet">some text here</li> <li data-colour="rgb(22,150,255), red, #2c3">some text here</li> <li data-colour="rgb(22,150,255) 50%, red 60%, #2c3 90%">some text here</li> </ul> </div>
Comments
Post a Comment