Posted By

jatkins on 04/09/14


Tagged

css html hex decimal color conversion Converter RGB hexadecimal colorcode colorcodes


Versions (?)

hex to rgb


 / Published in: JavaScript
 

Released into the public domain.

  1. function hexToDec(hexValue) {
  2. var decValue = 0;
  3.  
  4. for(var hexValuePos = 0; hexValuePos < hexValue.length; hexValuePos++) {
  5. var curChar = hexValue.charAt(hexValuePos),
  6. charCodeOfCurCharWhenCapitalized = curChar.toUpperCase().charCodeAt(0),
  7. decValueAtCurChar;
  8.  
  9. if(charCodeOfCurCharWhenCapitalized >= 65 && charCodeOfCurCharWhenCapitalized <= 70) // curChar is A/a/B/b/C/c/D/d/E/e/F/f
  10. decValueAtCurChar = charCodeOfCurCharWhenCapitalized - 55;
  11. else
  12. decValueAtCurChar = hexValue.charAt(hexValuePos);
  13.  
  14. decValue += decValueAtCurChar * Math.pow(16, hexValue.length - hexValuePos - 1);
  15. }
  16.  
  17. return decValue;
  18. }
  19.  
  20. function hexColorCodeToRGB(hexColorCode) {
  21. hexColorCode = hexColorCode.replace('#', '');
  22.  
  23. if(hexColorCode.length == 6) {
  24. var rgbValues = [];
  25.  
  26. for(var strPos = 0; strPos < hexColorCode.length; strPos += 2)
  27. rgbValues.push(hexToDec(hexColorCode.charAt(strPos).toString() + hexColorCode.charAt(strPos + 1).toString()));
  28.  
  29. rgbValues = {
  30. r: parseInt(rgbValues[0]),
  31. g: parseInt(rgbValues[1]),
  32. b: parseInt(rgbValues[2])
  33. };
  34.  
  35. rgbValues.red = rgbValues.r;
  36. rgbValues.green = rgbValues.g;
  37. rgbValues.blue = rgbValues.b;
  38.  
  39. return rgbValues;
  40. }
  41. else
  42. return false;
  43. }

Report this snippet  

You need to login to post a comment.