Skip to content

Instantly share code, notes, and snippets.

@LB-Digital
Created July 4, 2018 16:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LB-Digital/1711f25f989533cd27293dcf705fbb6a to your computer and use it in GitHub Desktop.
Save LB-Digital/1711f25f989533cd27293dcf705fbb6a to your computer and use it in GitHub Desktop.
JS function for converting a `HEX` colour code string with an alpha component, to `RGBA`.
function hexToRGBA(hex, opacity){
var rgba = "rgba(";
var inc = Math.abs(hex.length - 5);
for (var i = 1; i < hex.length; i+=inc){
var component = hex[i] + hex[i + (inc-1)];
rgba += parseInt(component, 16) + ",";
}
return rgba + opacity + ")";
}
// abs() gives absolute val (modulus); -5 just produces correct increment (1 or 2, based on length of 4 or 7... #f0f vs #ff00ff)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment