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.
If 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With