Isolate alpha value from background color, convert from string to number, then check

I am looking to check the background color value for an element and if the value is rgba value, I want to grab the alpha channel and see if it is below 1. But also return / exit if the background color is not rgba value i.e. if it is a hex or rgb value.

I have a feeling that regex is the best approach for this, but after a bit of head scratching I'm at a loss and regex isn't my strongest skill!

Here is what I already have and TODO is what I need a little help with

  var hasOpacity = false;
  var backgroundColor = $('.elemment-class').css('background-color');

  // backgroundColor could return:
  // (string / bool)
  // - null             - IGNORE
  // - transparent      - IGNORE
  // - #000             - IGNORE
  // - #FFFFFF          - IGNORE
  // - rgb(0,0,0)       - IGNORE
  // - rgba(0, 0, 0, 0.4)
  //                  ^ I need this value if it floating
  // - rgba(0, 0, 0, 1)
  //                 ^ Or this value if it integer


  function checkIfBackgroundHasAlpha(backgroundColor) {
     // @TODO If background value is any of the "IGNORE"s return because we don't need to do anything
     // only continue if the value is rgba

     // Its rgba so lets process
     if (isAplpa === true) {

        // @TODO First grab the alpha section of the rgba colour (REGEX perhaps?)
        // i.e rgba(255, 255, 255, 0.4)
        //                          ^
        // or rgba(6, 39, 123, 1)
        //                     ^

        // @TODO Then convert that value from a string to a number

        // Then run my validation
        if (alphaNumber < 1) {
           // Now that I know it got an opacity lets do what I need plus
           // set our var to true for later use
           hasOpacity = true;
        }

     }
  }

  // Run the check
  checkIfBackgroundHasAlpha(backgroundColor);

  if (hasOpacity) {
     // Yay we're here
     console.log('Yep we have Opacity on this');
  }

      

thank

+3


source to share


1 answer


You don't need a regex at all, you can simplify this approach a lot, given that you have a specific set of input types.



function hasOpacity(str) {
    if (str) {
        var tmp = str.split(',')[3];
        if (tmp) {
            var val = parseFloat(tmp);
            return (!isNaN(val) && val < 1);
        }
    }
    return false;
}
hasOpacity("rgba(0, 0, 0, 0.4)"); //true
hasOpacity("rgba(0,0,0,1)"); //false
hasOpacity(null); //false
hasOpacity("#FFFFFF"); //false

      

+3


source







All Articles