Skip to content

Instantly share code, notes, and snippets.

@Phoenix2k
Created December 16, 2013 01:12
Show Gist options
  • Save Phoenix2k/7980936 to your computer and use it in GitHub Desktop.
Save Phoenix2k/7980936 to your computer and use it in GitHub Desktop.
Convert RGB(A) values to #hexdecimal using jQuery.css()
// Convert RGB(A) values to #hexdecimal using jQuery.css()
// Original: http://jsfiddle.net/DCaQb/
// Note: This will not work on browsers which return 'color names' instead of rgb(a) values (i.e. IE8)
function rgba2hex( color_value ) {
if ( ! color_value ) return false;
var parts = color_value.toLowerCase().match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/),
length = color_value.indexOf('rgba') ? 3 : 2; // Fix for alpha values
delete(parts[0]);
for ( var i = 1; i <= length; i++ ) {
parts[i] = parseInt( parts[i] ).toString(16);
if ( parts[i].length == 1 ) parts[i] = '0' + parts[i];
}
return '#' + parts.join('').toUpperCase(); // #F7F7F7
}
// Example: Log rgb(a) and hex values to console()
$('.sg-swatch').on('click', function() {
var rgba_value = $(this).css('background-color'),
hex_value = rgba2hex(rgba_value),
log_rgba = rgba_value ? rgba_value : 'none',
log_hex = hex_value ? hex_value : 'none';
console.log('RGB(alpha): %c' + log_rgba, 'color: ' + hex_value + ';');
console.log('Hex: %c' + log_hex, 'color: ' + hex_value + ';');
});
@JoeSz
Copy link

JoeSz commented Feb 27, 2016

Thank you very much for the code!
I had 2 issue do.
First, if color start with rgba then length returns 0 which in this case can be interpreted as false, so the last part will not processed.
Second, if it is rgba then parts.join('') add the alpha value as well, like for rgba(255,255,255,0.5) -> #FFFFFF0.5.
I suggest the following modification:
var parts = color_value.toLowerCase().match(/^rgba?((\d+),\s_(\d+),\s_(\d+)(?:,\s*(\d+(?:.\d+)?))?)$/);
if (color_value.indexOf('rgba') === false) { //check if it is 0 (start with rgba) or false (it is NOT rgba)
length = 2;
} else{
length = 3;
delete(parts[4]); //delete the alpha value prevent adding it by parts.join
};
Best Regards
Joe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment