Adding alpha channel to background color using jQuery / JavaScript

I have a jQuery function that adds Alpha to the background color when an event occurs.

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 to add / change alpha channel?

Any help would be greatly appreciated.

+5
source share
1 answer

If you want to change the rgba css property using javascript, you will need to use the replace method, however you can improve your code as follows:

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 helps you.

+3
source

All Articles