JQuery function to add alpha to bg element

I am trying to make a function that checks the bg element and changes its bg to the given alpha channel. The function has the following form:

$.fn.bgalpha = function(alpha) {
    var bg = $(this).css('background-color');
    //...
}

But: chrome returns bg as rgb when normal color is set, and as rgba with zero when there is no bg, i.e. 8 always returns hex, ie9 returns "transparent" when there is no bg and rgb, when there is bg, etc. So many different cases.

What I want to do is → get r, g, b from the bg color of the object, add the 'a' channel to it and set the bg element to rgba with all the values. But from a simple thing, making it becomes complicated and complicated when we talk about cross-viewing.

Do you have any ideas on how to work with these colors as a "single-user" way? In different cases, I get the values ​​"none", "transparent", "rgba", "rgb" or "hex" as the initial value of bg

+5
source share
2 answers

Enable the jQuery Color plugin (officially authorized) and use its method .alpha().

The following code snippet will change the background color thisto 50% transparent:

var clr2 = $.Color(this,'background-color').alpha(0.5);
$(this).css('background-color', clr2.toRgbaString());

or as one line:

$(this).css('background-color', $.Color(this,'background-color').alpha(0.5).toRgbaString());

http://jsfiddle.net/mblase75/aea3h/

+2
source
$.fn.bgalpha = function(alpha)
{
    return $(this).each(function(){
        $(this).css('background-color', $.Color(this,'background-color').alpha(alpha).toRgbaString());          
    });
}

Using the Blazemonger solution is the final code.

Using:

$('.something').bgalpha(0.8);

And this requires jquery.color.js(7kb after minifessing)

0
source

All Articles