Posted By

joshuabaker on 11/02/09


Tagged

hex jquery colour color conversion RGB


Versions (?)

jQuery.rgbToHex


 / Published in: JavaScript
 

  1. /**
  2.  * jQuery.rgbToHex - Converts an RGB string to a HEX string (forces length 6)
  3.  * @author Joshua Baker
  4.  * @version 1.0.0
  5.  */
  6. ;(function($){
  7. $.extend({
  8. rgbToHex: function(rgbString) {
  9. var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
  10. if (!parts)
  11. {
  12. if (rgbString.length < 6) {
  13. var parts = rgbString.split('');
  14. delete (parts[0]);
  15. for (var i = 1; i <= 3; ++i)
  16. {
  17. if (parts[i].length == 1) parts[i] = parts[i] + parts[i];
  18. }
  19. }
  20. }
  21. else
  22. {
  23. delete (parts[0]);
  24. for (var i = 1; i <= 3; ++i)
  25. {
  26. parts[i] = parseInt(parts[i]).toString(16);
  27. if (parts[i].length == 1) parts[i] = parts[i] + parts[i];
  28. }
  29. }
  30. return '#' + parts.join('');
  31. }
  32. });
  33. })(jQuery);
  34.  
  35.  
  36.  
  37. /**
  38.  * jQuery.rgbToHex - Converts an RGB string to a HEX string (forces length 6)
  39.  * @author Joshua Baker
  40.  * @version 1.0.0
  41.  */
  42. ;(function(a){a.extend({rgbToHex:function(d){var c=d.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);if(!c){if(d.length<6){var c=d.split("");delete (c[0]);for(var b=1;b<=3;++b){if(c[b].length==1){c[b]=c[b]+c[b]}}}}else{delete (c[0]);for(var b=1;b<=3;++b){c[b]=parseInt(c[b]).toString(16);if(c[b].length==1){c[b]=c[b]+c[b]}}}return"#"+c.join("")}})})(jQuery);

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: joshuabaker on November 3, 2009

Broken in IE. See fixed version here: http://snipplr.com/view/22364/jqueryrgbtohex/

You need to login to post a comment.