Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the background-image property to a linear gradient using jQuery's css method?

When I use this on my page the background gradient doesn't appear (I'm only worried about Safari and Firefox at the moment):

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

I tried using just one or the other as well in the appropriate browsers, but no luck there.

I can just use an inline style attribute for the element in my code, but I'd rather not do it that way if there's a way to do it using jQuery's API.

like image 461
natlee75 Avatar asked Sep 08 '11 21:09

natlee75


People also ask

How do you make a linear gradient in jQuery?

$(element). css({background: "-webkit-gradient(linear,left bottom,right bottom,color-stop(0.50, rgb(194,231,255)),color-stop(0.50, rgb(255,255,255)"});

Which function in CSS is used to set the linear gradient as the background image?

The linear-gradient() function sets a linear gradient as the background image. To create a linear gradient you must define at least two color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along with the gradient effect.

Which CSS property is used to create gradient background colors?

linear-gradient() The linear-gradient() CSS function creates an image consisting of a progressive transition between two or more colors along a straight line.

Which CSS property is used to set the background image of an element?

The background-image CSS property sets one or more background images on an element.


1 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:

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

Tested on Chrome and FF 6

like image 135
Sam Martin Avatar answered Oct 07 '22 18:10

Sam Martin