7

I have a jQuery function that adds an Alpha channel to a background-color when an event occur.

Here is my jsFiddle.

CSS

div { background-color: rgb(100,100,100); }

JavaScript

function addAlphaChannel() {
    var oldBGColor = $('div').css('backgroundColor'); //rgb(100,100,100)
    var newBGColor = oldBGColor.replace('rgb', 'rgba').replace(')', ',.8)'); //rgba(100,100,100,.8)

    $('div').css({ backgroundColor: newBGColor });
}

This code works fine, however I wonder if there is a better way of adding/changing alpha channel?

Any help will be much appreciated.

Lior Elrom
  • 19,660
  • 16
  • 80
  • 92
  • use the opacity css property? (but this is not only for the bg-color) – bwoebi May 21 '13 at 20:21
  • @bwoebi An opacity will effect ALL my element's children – Lior Elrom May 21 '13 at 20:22
  • 1
    Yes, I just said this. But no, I don't see any alternative. – bwoebi May 21 '13 at 20:23
  • How does your code work- where does the string called 'color' come from? – kennebec May 21 '13 at 22:41
  • @kennebec It was a typo mistake. Thx for your comment. Hope it make sense now. – Lior Elrom May 22 '13 at 00:41
  • 1
    try this http://stackoverflow.com/questions/8177964/in-javascript-how-can-i-set-rgba-without-specifying-the-rgb – James Daly May 22 '13 at 02:38
  • @JamesDaly This solution is using strings as well. My solution is simpler but I can't find a nicer and elegant way of doing it. Thx! – Lior Elrom May 22 '13 at 02:49
  • @JamesDaly I guess I can and I also know how to target my element directly but I'm looking for some more robotic solution that can work with any given element. – Lior Elrom May 22 '13 at 03:00
  • I *think* you're confined to string manipulation, because CSS is sent as raw text. The SO answer that @JamesDaly linked to above has a quite elegant regex manipulation that's more robust than your string replace solution. – glifchits Sep 19 '13 at 20:51

1 Answers1

3

If you want to change the rgba css property using javascript, you'll need to use the replace method, however, you can improve your code like this:

CSS

 div { background-color: rgba(100, 100, 100, 1.0); }

JS

function addAlphaChannel() {
    var oldBGColor = $('div').css('background-color'), //rgb(100,100,100),
        newBGColor = oldBGColor.replace(/[^,]+(?=\))/, '0.8'); //rgba(100,100,100,.8);

    $('div').css({ backgroundColor: newBGColor });
}

Hope this can help you.

Lior Elrom
  • 19,660
  • 16
  • 80
  • 92
lucho99
  • 172
  • 3
  • Yes, it's another way of the same thing - using strings, Even thou I'm not sure as per as your RegEx syntax (try it yourself), in terms of time/code efficiency, specific replacement (like 'rob' => 'rgba') is faster than using a RegEx engine. – Lior Elrom Oct 25 '13 at 16:29