Reputation: 503
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
Upvotes: 5
Views: 1215
Reputation: 503
$.fn.bgalpha = function(alpha)
{
return $(this).each(function(){
$(this).css('background-color', $.Color(this,'background-color').alpha(alpha).toRgbaString());
});
}
Using Blazemonger's solution - this is final code.
Using:
$('.something').bgalpha(0.8);
And it requires jquery.color.js
(7kb after minifing)
Upvotes: 0
Reputation: 92903
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/
Upvotes: 2