Search code examples
jqueryhtmlcssbackground-color

How to extract the alpha transparent value from RGBA background color in jQuery?


I need to extract the RGBA value's alpha transparent value to check whether the background color is transparent or not. How can I do that using jQuery?


Solution

  • You can get the color style property, split it by the commas within the RGBA declaration and then parseFloat to get the numerical value of the alpha channel.

    I added a check to console a message if there is no alpha channel listed (ie an rgb value only.

    var bgCol = $('div').css('backgroundColor');
    console.log('Background color is ' + bgCol);
    
    var alpha = parseFloat(bgCol.split(',')[3]);
    
    isNaN(alpha)
      ? console.log('no alpha channel')
      : console.log('alpha channel value is ' + alpha); // gives alpha channel value is 0.1
    div {
      background-color: rgba(0,0,0, 0.1);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
     <p>This is a test </p>
    </div>