How to set background-image property to linear gradient using jQuery css?

When I use this on my page, the background gradient does not appear (at the moment, Safari and Firefox bother me):

$("#myElement").css({ backgroundImage: "-webkit-gradient(linear, top, bottom, from(black), to(white)", backgroundImage: "-moz-linear-gradient(top, black, white)" }); 

I tried to use only one or the other as well in the respective browsers, but no luck.

I can use the inline style attribute for an element in my code, but I would prefer not to do this if there is a way to do this using the jQuery API.

+7
source share
3 answers

The following works for me.

 $("#myElement").css({ background: "-webkit-gradient(linear, left top, left bottom, from(#000000), to(#FFFFFF))"}).css({ background: "-moz-linear-gradient(top, black, white)" }); 

jsFiddle Demo

Changes:

  • instead of backgroundImage
  • top, bottom to: top left, bottom left
  • Missing closing parentheses from webkit gradient
  • changed black and white to # 000000 and #FFFFFF
  • added second .css

Tested on Chrome and FF 6

+5
source

I tried this in Firefox 6.0.1 and it works for me

 $(function() { $("#myElement").css({ backgroundImage: "-webkit-gradient(linear, top, bottom, from(black), to(white)", backgroundImage: "-moz-linear-gradient(top, black, white)" }); }); 

HTML

 <div id="myElement">testing</div> 
0
source

There may be a difference between newer versions and webkit versions:

How to combine background image gradient and CSS3 with the same element?

I have a small example of working with the following:

 $(function(){ $("#myElement").css("background-image", "-webkit-linear-gradient(top, #000000, #ffffff)"); $("#myElement").css("background-image", "-moz-linear-gradient(top, black, white)"); }); 

here is the fiddle:

http://jsfiddle.net/Hmmpd/1/

Edit:

Odd using css "map" version of css works in Firefox, but not in my version of Chrome. That is, firefox works for me, but not chrome:

 $(function(){ $("#myElement").css({backgroundImage: "-webkit-linear-gradient(top, #000000,#ffffff)",backgroundImage: "-moz-linear-gradient(top, black, white)"}); }); 
0
source

All Articles