20

I have the following code to get the background color of an element.

var currentColor = $(this).css('background-color');

which returns something like rgb(123,123,123)

What I now want to do convert this to rgba and show it at 0.75 alpha

So returning something like rgba(123,123,123,0.75)

Any ideas?

Tom
  • 12,776
  • 48
  • 145
  • 240
  • have you considered regex? – nicolallias May 12 '14 at 12:19
  • Any reason you want to change it to rgba instead of using jQuerys $.fadeTo-function? rgba won't work in older browsers. I would do $(this).fadeTo(0, 0.75) instead. – ninja May 12 '14 at 12:26
  • @ninja Can you submit your comment as an answer so I can up vote it. Its a better solution if you are already using jQuery. – Anton Dec 28 '15 at 18:47

3 Answers3

31

Since jQuery always seems to return the color like rgb(r, g, b) for elements that have no alpha, you could simply use:

$(this).css('background-color').replace(')', ', 0.75)').replace('rgb', 'rgba');

Just make sure the background color isn't rgba already:

var bg = $(this).css('background-color');
if(bg.indexOf('a') == -1){
    var result = bg.replace(')', ', 0.75)').replace('rgb', 'rgba');
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • caution, if `this` has no background-color set, `css('background-color')` will return `undefined`. – Andre Figueiredo Feb 15 '16 at 17:14
  • 1
    I've added a jsperf test showing diff of using `replace` vs `substr` to achieve this. `substr` is clearly the winner. https://jsperf.com/replace-rbg-with-rgba – ctrlplusb Aug 11 '17 at 12:43
2

http://regex101.com/r/lT9iM4

var re = /(rgb)\(([0-9]+),\s+([0-9]+),\s+([0-9]+)/; 
var currentColor = $(this).css('background-color');
var subst = 'rgba($2,$3,$4,0.75'; 

$(this).css('background-color', currentColor.replace(re, subst));

Another solution using regex. But as Cerbrus mentioned, using regex for something this simple is overkill.

Community
  • 1
  • 1
Henrik Peinar
  • 2,181
  • 18
  • 22
2

Another regex try http://jsfiddle.net/hc3BA/

var colour = 'rgb(123,123,123)',
new_col = colour.replace(/rgb/i, "rgba");
new_col = new_col.replace(/\)/i,',0.75)');
nicolallias
  • 1,055
  • 2
  • 22
  • 51