Lior Elrom Lior Elrom - 6 months ago 34
HTML Question

Add Alpha Channel to Background Color using jQuery / JavaScript

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.

Answer

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.