0

Scenario : Using pure Javascript only (no libraries), I need to increment (or decrement) the background colour opacity of an HTML element without affecting the opacity of any child element. The new opacity can be anywhere in the range of fully opaque to fully transparent. Support for browsers prior to IE9 is not required hence the chosen method to accomplish this is by using background-color property from getComputedStyle. I have only seen this return a string in two formats (using pure white as an example) :

  • rgba(255, 255, 255, 0.5) when opacity is applied.
  • rgb(255, 255, 255) when fully opaque - it changes to this format when opacity is 1.

I need to reset the background colour in the format, rgba(255, 255, 255, 0.5)

Code fragment :

    myBG = window.getComputedStyle( myElement, null ).getPropertyValue( "background-color" );
    myElement.style.backgroundColor = myBG.replace( /(.*)\((\s*\d+)\,(\s*\d+)\,(\s*\d+)(?:\,|\))(.*)/ , 'rgba( $2, $3, $4, ' + myNewOpacity.toString() + ' )' );

This works in the limited testing I have conducted - However :

Question 1. I am a beginner to Javascript and web development. Will I get any return formats that do not match the two above (cross browser compatibility issue) ?

Question 2. I am a complete novice to regular expressions. My solution seems heavy and/or inelegant. Is there a better regular expression I can use ? Is there a better alternative to using replace/regex ?

Harun Diluka Heshan
  • 1,155
  • 2
  • 18
  • 30

1 Answers1

0
  1. As far as I know, there are no other possible return values. If opacity is set, there can only be an rgba(...) return value, so in the mindset of defensive programming, you should only parse and modify the value if it is rgba (See also In Javascript how can I set rgba without specifying the rgb?)
  2. See the above link for an easier to read solution without regex.
Laurent P
  • 36
  • 2