infatti
infatti

Reputation: 11

Declaring CSS3 Gradient with jQuery

I am adding a css3 gradient to a button. I think jQuery is combining all of my cross-browser 'background-image' declarations as just one declaration (the last 'background-image' that it finds). Is there a better way to write the jQuery so it presents to the browser all the cross-browser css as it normally would?

Here is my jQuery:

        $('.button').css({
        'background-color' : FromGradientColor ,
        'background-image' : '-webkit-gradient(linear, 0% 0%, 0% 100%, from('+ FromGradientColor +'), to('+ ToGradientColor +'))' ,
        'background-image' : '-webkit-linear-gradient(top,' + FromGradientColor +', ' + ToGradientColor +')' ,
        'background-image' : '-moz-linear-gradient(top,' + FromGradientColor +', ' + ToGradientColor +')' ,
        'background-image' : '-ms-linear-gradient(top,' + FromGradientColor +', ' + ToGradientColor +')' ,
        'background-image' : '-o-linear-gradient(top,' + FromGradientColor +', ' + ToGradientColor +')' 
    });

This is what I want jQuery to present to the browser (except the colors which are determined by my variables in jQuery):

background-color: #ddd;
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#eee), to(#ccc));
background-image: -webkit-linear-gradient(top, #eee, #ccc);
background-image: -moz-linear-gradient(top, #eee, #ccc);
background-image: -ms-linear-gradient(top, #eee, #ccc);
background-image: -o-linear-gradient(top, #eee, #ccc);
background-image: linear-gradient(top, #eee, #ccc);
text-shadow: 0 1px 0 rgba(255,255,255,.8);

Upvotes: 1

Views: 1742

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24637

Put the styles into a class, such as this less example:

@bgcolor: #ddd;

.gradient(@from: #eee, @to: #ccc) 
  {
  background-color: @bgcolor; 
  background-image: -webkit-linear-gradient(top, @from, @to); 
  background-image: -moz-linear-gradient(top, @from, @to); 
  background-image: -ms-linear-gradient(top, @from, @to); 
  background-image: -o-linear-gradient(top, @from, @to); 
  filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=@{from}, endColorstr=@{to})"; 
  -ms-filter: "'progid:DXImageTransform.Microsoft.gradient (GradientType=0, startColorstr=@{from}, endColorstr=@{to})'"; 
  }

Then reference it as such:

$('.button').addClass("gradient")

Upvotes: 1

Related Questions