I’m having an issue where I’m trying to update the background gradient of an element with JavaScript based on values I specify.
I tried this route:
elem.style.backgroundImage = '-webkit-gradient(radial, '+x+' '+y+', 0, '+x+' '+y+', 800, from(#ccc), to(#333)), -moz-radial-gradient('+x+'px '+y+'px, circle cover, #ccc 0, #333 100%)';
Since Webkit and Gecko have two different syntaxes for CSS3 gradients, I need to specify both. However, the above code doesn’t work. It works if I only have just the Gecko syntax or just the Webkit syntax, not both.
I think you can check for CSS gradient support, but my question is, is there a way to check which syntax needs to be used without browser sniffing? Keep in mind that I need to set my gradients this way since the x and y coordinates of the gradient change dynamically.
Hope this makes sense, thanks.
Edit The below is useful for other reasons, but in fact, I don’t think it helps with the OP’s problem of knowing whether to use the WebKit or Firefox symtax! (Doh) It helps with knowing whether the gradients can be used at all.
Edit again But! Looking at the Modernizr source shows us how to do it with a feature test (they’re clever, those folks). You can probably figure it out by looking at the source yourself, but here’s a quickly hacked-together example:
You might want to use Modernizr for this. It detects the relevant syntax and provides a way for you to use a single CSS file with both syntaxes.
Sample gradient code from the docs:
(Edit In the above, I’ve removed a line from the end of the
.cssgradients button.glossyrule that looked to me like an error in the docs.)See that
.cssgradientsclass? When you run Modernizr, it detects whether that’s the relevant syntax and if so adds the class to yourhtmlelement, which turns on the descendant selector.cssgradients button.glossyso that rule gets applied.This is, sadly, all dependent on the browser having Javascript enabled.