Thursday, 28 June 2018

Colour shading with JavaScript

Shading a colour can be an utter pain but when I came across this script from CSS-TRICKS I was happy as a pig in muck. At least I was until I had to change the colour received via a call to getComputedStyle. getComputedStyle returns the colour in this format rgb(RedDecimalNumber, GreenDecimalNumber, BlueDecimalNumber) (red is rgb(255,0,0)) rather than the #RedHexadecimalNumberGreenHexadecimalNumberBlueHexadecimalNumber (red is #ff0000). The original script I was using was the one linked above so I had to convert the colour from getComputedStyle to hexadecimal, alter its shade and return it back to the original element's style as hexadecimal again.

This method seemed overly complicated, and I clocked that I didn't need to return it to the element as hexadecimal but could use it just as an RGB string in the inline CSS. Then I got to looking at the original script and realised that as getComputedStyle returns an RGB string, I could rewrite the original function to use a regex function and return that to the inline CSS instead. The following is the function:

o.replace(/\d+/g,c=>~~c+s>=255?255:~~c+s<=0?0:~~c+s)

I always forget that replace can take a function as the second argument but in this instance, it's cool that it does. The following is a less ES6y version:

o.replace(/\d+/g, function(c){
  if((parseInt(c, 10) + s) >= 255){
    return 255
  }else{
    if((parseInt(c, 10) + s) <= 0){
      return 0
    }else{
      return parseInt(c, 10) + s
    }
  }
})

Fun eh?