Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 223
Lior Elrom Avatar asked May 21 '13 20:05

Lior Elrom


1 Answers

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.

like image 124
lucho99 Avatar answered Oct 09 '22 20:10

lucho99