Dave
Dave

Reputation: 11862

Applying css3 gradients with jQuery

Eventually, I wish to dynamically alter gradients based on different things, but how do I get jquery to apply a css3 gradient?

 //works
 $(element).css("background-image", "url(http://www.google.co.uk/images/logos/ps_logo2.png)");  

 //doesn't work
 $(element).css("background-image","-webkit-gradient(linear,left bottom,right bottom,color-stop(0.50, rgb(194,231,255)),color-stop(0.50, rgb(255,255,255))");

 //doesn't work
 $(element).css("background-image","-moz-linear-gradient(left center,rgb(194,231,255) 28%,rgb(255,255,255) 28%");

What am I missing? I've also tried

 $(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)"});

Are these approaches not valid?

Upvotes: 17

Views: 48407

Answers (6)

WSimpson
WSimpson

Reputation: 41

Another option is to use the jQuery addClass method. This allows you to dynamically add and remove classes and therefore any formatting associated with that class including gradients.

Upvotes: 4

ADamian17
ADamian17

Reputation: 1

try this

<div class="mygradient" />

$( '.mygradient' ).css( 
    "background-image", 
    "linear-gradient( to right, #dc8a8a 50%, red 10% )" 
);

Upvotes: 0

Dutchie432
Dutchie432

Reputation: 29170

Your second approach looks OK... Maybe you need to css styles for non-webkit browsers as well... Cross-Browser CSS Gradient

This works for me in Chrome

$('#block').css({
    background: "-webkit-gradient(linear, left top, left bottom, from(#ccc), to(#000))" 
});

Also have a look at: http://www.colorzilla.com/gradient-editor/

Upvotes: 22

Sanu Uthaiah Bollera
Sanu Uthaiah Bollera

Reputation: 937

Here is a small piece of example...

$("p").css({background:'linear-gradient(red,blue,red)'});

Upvotes: 3

Puneet Lamba
Puneet Lamba

Reputation: 791

I'm using the hyphenated syntax in the JSON format (I always use the JSON format to be consistent). And it's working fine in both Chrome and Firefox.

For example:

$("#googleFeed div:even").css({
    'background':'-webkit-linear-gradient(top,white,black)',        
});

Upvotes: 1

motown
motown

Reputation: 11

When using .css() in jquery, I believe you have to use the shortened versions of the attributes. For example, margin-left would be marginLeft

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

Upvotes: -2

Related Questions