Hex to RGB or RGBA transluder


/ Published in: JavaScript
Save to your folder(s)

Transform a color given in hex to RGB. An optional opacity argument also enables RBGA.


Copy this code and paste it in your HTML
  1. function hex2rgb(hex, opacity) {
  2. var rgb = hex.replace('#', '').match(/(.{2})/g);
  3.  
  4. var i = 3;
  5. while (i--) {
  6. rgb[i] = parseInt(rgb[i], 16);
  7. }
  8.  
  9. if (typeof opacity == 'undefined') {
  10. return 'rgb(' + rgb.join(', ') + ')';
  11. }
  12.  
  13. return 'rgba(' + rgb.join(', ') + ', ' + opacity + ')';
  14. };

URL: http://madr.se/blog/151

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.