Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function to add alpha to element bg

Tags:

jquery

Im trying to make function that checks element's bg and changes its bg to have given alpha channel. Function has this 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's when there is no bg, ie 8 always returns hex, ie9 returns 'transparent' when there is no bg and rgb when there is bg etc. So much different cases.

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

Have you any idea how to operate with those colors some 'uniwersal' way? In different cases I get values 'none', 'transparent', 'rgba', 'rgb' or 'hex' as initial value of bg

like image 476
OPOPO Avatar asked Nov 04 '22 04:11

OPOPO


1 Answers

Include the jQuery Color plugin (it's officially sanctioned) and use its .alpha() method.

The following code snippet will change the background color of this so it's 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/

like image 118
Blazemonger Avatar answered Nov 15 '22 06:11

Blazemonger