0

I'm creating a small JavaScript API for my homepage with jQuery. At a point later in the code, I'm attaching an object containing css to an element via: $(element).css(theVariable);

The result should be equivalent to the following CSS code for example:

h3 {
 background-color: rgb(0, 80, 0);
 background-color: rgba(0, 80, 0.75);
}
The reason is obviously to have a transparent color but also work in older versions of browsers which don't support "rgba()".

How would I fill my theVariable so the effect when calling css(theVariable) is the same as the css-code above? I cannot use something like

theVariable = {};
theVariable['backgroundColor'] = 'rgb(0, 80, 0)';
theVariable['backgroundColor'] = 'rgba(0, 80, 0, 0,3)';

Since the RGBA value would always overwrite the RGB value.

Is there any way to circumvent this problem?

Cœur
  • 37,241
  • 25
  • 195
  • 267
DragonGamer
  • 834
  • 3
  • 9
  • 27

2 Answers2

0

I would suggest to do the opposite in your javascript. As you don't know if the browser has support to rgba, you can do:

theVariable = {};
theVariable['backgroundColor'] = 'rgba(0, 80, 0, 0,3)';
if(!theVariable['backgroundColor']) // Browser without support will return undefined
  theVariable['backgroundColor'] = 'rgb(0, 80, 0)';
  • Thank you for the answer, but that's doesn't work unfortunately (just tested). This code only assigns strings to the variable. There's no CSS-inrepretation yet! – DragonGamer Jun 21 '15 at 21:47
  • @DragonGamer consider a similar approach that uses [computed CSS](http://stackoverflow.com/q/754607/139010). – Matt Ball Jun 21 '15 at 22:19
0

I'd suggest using Modernizr to check for various features that legacy browsers are lacking. Then in your case CSS would look something like this:

.no-rgba h3 {
    rgb(0, 80, 0);
}
.rgba h3 {
    rgba(0, 80, 0, 0.3);
}

Please see this fiddle.

kaaposc
  • 174
  • 1
  • 9