Lior Elrom Lior Elrom - 2 years ago 151
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.


div { background-color: rgb(100,100,100); }


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 Source

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:


 div { background-color: rgba(100, 100, 100, 1.0); }


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download