Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 620
Dave Avatar asked May 16 '11 11:05

Dave


People also ask

Can you do gradients in CSS?

CSS gradients let you display smooth transitions between two or more specified colors. CSS defines three types of gradients: Linear Gradients (goes down/up/left/right/diagonally) Radial Gradients (defined by their center)

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

Is it possible to combine a background image and CSS3 gradients?

You can combine a background-image and CSS3 gradient on the same element by using several backgrounds. In our example below, we set the height and width of our <div> and add a background. Then, we set the background image fallback using the “url” value of the background-image property.

Can you do gradient text in CSS?

But gradient text can be achieved in CSS, it just requires a few extra steps. It's best to start with some big bold text. This will make the gradient more visible and the text more readable.


3 Answers

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/

like image 99
Dutchie432 Avatar answered Oct 31 '22 10:10

Dutchie432


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.

like image 4
WSimpson Avatar answered Oct 31 '22 10:10

WSimpson


Here is a small piece of example...

$("p").css({background:'linear-gradient(red,blue,red)'});
like image 3
Sanu Uthaiah Bollera Avatar answered Oct 31 '22 11:10

Sanu Uthaiah Bollera