I have a jQuery function that adds an Alpha channel to a background-color when an event occur.
Here is my jsFiddle.
CSS
div { background-color: rgb(100,100,100); }
JavaScript
function addAlphaChannel() {
var oldBGColor = $('div').css('backgroundColor'); //rgb(100,100,100)
var newBGColor = oldBGColor.replace('rgb', 'rgba').replace(')', ',.8)'); //rgba(100,100,100,.8)
$('div').css({ backgroundColor: newBGColor });
}
This code works fine, however I wonder if there is a better way of adding/changing alpha channel?
Any help will be much appreciated.
I have a jQuery function that adds an Alpha channel to a background-color when an event occur.
Here is my jsFiddle.
CSS
div { background-color: rgb(100,100,100); }
JavaScript
function addAlphaChannel() {
var oldBGColor = $('div').css('backgroundColor'); //rgb(100,100,100)
var newBGColor = oldBGColor.replace('rgb', 'rgba').replace(')', ',.8)'); //rgba(100,100,100,.8)
$('div').css({ backgroundColor: newBGColor });
}
This code works fine, however I wonder if there is a better way of adding/changing alpha channel?
Any help will be much appreciated.
Share Improve this question edited May 11, 2016 at 23:32 Lior Elrom asked May 21, 2013 at 20:20 Lior ElromLior Elrom 21k16 gold badges82 silver badges94 bronze badges 9- use the opacity css property? (but this is not only for the bg-color) – bwoebi Commented May 21, 2013 at 20:21
- @bwoebi An opacity will effect ALL my element's children – Lior Elrom Commented May 21, 2013 at 20:22
- 1 Yes, I just said this. But no, I don't see any alternative. – bwoebi Commented May 21, 2013 at 20:23
- How does your code work- where does the string called 'color' e from? – kennebec Commented May 21, 2013 at 22:41
- 1 try this stackoverflow./questions/8177964/… – James Daly Commented May 22, 2013 at 2:38
1 Answer
Reset to default 3If you want to change the rgba css property using javascript, you'll need to use the replace method, however, you can improve your code like this:
CSS
div { background-color: rgba(100, 100, 100, 1.0); }
JS
function addAlphaChannel() {
var oldBGColor = $('div').css('background-color'), //rgb(100,100,100),
newBGColor = oldBGColor.replace(/[^,]+(?=\))/, '0.8'); //rgba(100,100,100,.8);
$('div').css({ backgroundColor: newBGColor });
}
Hope this can help you.