In Javascript How Can I Set Rgba Without Specifying the Rgb?

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)";
1

5 Answers

You got the string, replace whatever
'rgba(1,1,1,0.3)'.replace(/[^,]+(?=\))/, '0.5')

1

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!
2

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});
}
1

Does this help?

This may help in addition.

Convert RGBA color to RGB

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest