33

I have an HTML element whose background colour is set with rgba()

<div style="background-color: rgba(2,100,100,0);"> </div>

Then I have a timer that makes the background slowly fade in by changing the opacity value of the element in javascript

myEle.style.backgroundColor = "rgba(x,x,x,0.1)"; // I have to know the rgb values to update the alpha value

Is there a way to set the a value of rgba() without changing/knowing the rgb values?

Maybe I can do something like this?

var r = myEle.style.r;
var g = myEle.style.g;
var b = myEle.style.b;
myEle.style.backgroundColor = "rgba("+r+","+g+","+b+",0.1)";
Emil
  • 8,449
  • 3
  • 27
  • 44
sazr
  • 24,984
  • 66
  • 194
  • 362
  • 2
    Depending on your situation opacity may work for you. However it would fade the whole element not just the background, so I'm assuming it probably is not an option. – qw3n Nov 18 '11 at 04:59

5 Answers5

27

You got the string, replace whatever

var oldCss = 'rgba(1,1,1,0.3)',
newOpacity = '0.5',
newCss = oldCss.replace(/[^,]+(?=\))/, newOpacity);

console.log(oldCss, "replaced with", newCss);
Mike Szyndel
  • 10,461
  • 10
  • 47
  • 63
Leonid
  • 3,121
  • 24
  • 31
17

After some playing around, and the discovery of getComputedStyle, I have put together this.

<!DOCTYPE HTML>
<html>
  <head>
    <style type="text/css">
      #element {
        background-color: rgb(10,10,10);
        background-color: rgba(10,10,10,1);
      }
    </style>
    <script type="text/javascript">      
      HTMLElement.prototype.alpha = function(a) {
        current_color = getComputedStyle(this).getPropertyValue("background-color");
        match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color)
        a = a > 1 ? (a / 100) : a;
        this.style.backgroundColor = "rgba(" + [match[1],match[2],match[3],a].join(',') +")";
      }
    </script>
  </head>
  <body>
    <div id="element">
      This is some content.
    </div>
    <script type="text/javascript">
      e = document.getElementById('element');
      e.alpha(20);
    </script>
  </body>
</html>
  • Make sure you define in your css your values, and cascade because RGBA is CSS3.
  • Also see that you can pass in a number >1 for alpha and it will divide by 100 for you (I hate working with decimals when thinking percentages).
  • Enjoy!
Rob Cooper
  • 28,567
  • 26
  • 103
  • 142
  • 1
    I have edited your code to fix its more obvious shortcomings. Some feature tests are still missing. Note that this could be even simpler as we do not really care for the format of the original RGB values, and not for the possible value after the blue RGB component. Also note that division always carries with it the possibility of a rounding error, and should be avoided. – PointedEars Nov 20 '11 at 00:07
  • For some reason my edit was not accepted. JFTR, there are several things wrong with the original code: Relying on element prototype augmentation, undeclared variables, missing document.defaultView, missing second getComputedStyle() argument, /…/g.exec(s) instead of s.match(/…/), repeated element reference instead of slice, insufficient number and missing percent match (if one wants to adhere to CSS 2.1 / 3), and one unnecessary assignment. – PointedEars Nov 22 '11 at 17:32
1

I had do this too but ended up writing something a little more specific. I put it in a jQuery plugin that accepts a min and max opacity:

$.fn.setAlpha = function ( options ) {
    var settings = $.extend({
        alpha: 0.5,
        min: 0,
        max: 1
    }, options );
    return this.each(function() {
        var color = $(this).css('background-color');
        if (color.substring(0,4) === 'rgba') {
            var a;
            if (settings.alpha <= settings.min) {
                a = settings.min;
            } else if (settings.alpha >= settings.max) {
                a = settings.max;
            } else {
                a = settings.alpha;
            }
            var rgba = color.replace(/[^,]+(?=\))/, a);
            $(this).css('background-color', rgba);
        }
    });
}

$.fn.getAlpha = function () {

    var color = this.css('background-color');
    if (color.substring(0,4) === 'rgba') {
        var alpha = color.split(',');
            alpha = alpha[alpha.length - 1].trim();
            alpha = alpha.substring(0, alpha.indexOf(")"));
        return alpha;
    } else {
        return 1;
    }
}

then you use them to do something like this to set a div to transparent and fade it to its original opacity as you scroll down:

//get original opacity
var originalOpacity = $('#myDiv').getAlpha(); 

//set new opacity
//it will be 0 at the top of the page
var newOpacity = $(window).scrollTop()/500;
$('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity}); 

//on scroll fade new opacity to originalOpacity at 500px down
$(window).scroll( function() {
     var newOpacity = $(window).scrollTop()/500;
     $('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity});
}
Jonathon
  • 113
  • 7
0

Does this help?

http://www.phpied.com/rgb-color-parser-in-javascript/

This may help in addition.

Convert RGBA color to RGB

Community
  • 1
  • 1
r0ast3d
  • 2,639
  • 1
  • 14
  • 18
0

You could also use elem.style.opacity=0.5 or in html style="opacity:0.5". It is important to note that the child nodes will fade too.

EpicDavi
  • 6,732
  • 3
  • 19
  • 20
rekire
  • 47,260
  • 30
  • 167
  • 264
  • 16
    Opacity is not the same as background opacity via alpha channel. This is not what the question is asking for. Opacity will reduce the opacity of the background AND the contents of the div while the question wants a way to do it for the background alone. – Frug Nov 21 '11 at 18:34