Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Created July 10, 2013 08:39
Show Gist options
  • Save ourmaninamsterdam/5964521 to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/5964521 to your computer and use it in GitHub Desktop.
Converts a HEX to RGB and vice versa. Takes a 6 character HEX or a single R/G/B value.
/**
* convert_color()
* Converts a HEX to RGB and vice versa
* @param {String or Integer} color Takes a full 6 character HEX "ff5500" / RGB colour value 167 (< 255)
* @return {str} returns a HEX or RGB (space delimited), depending on input
*
*/
function convert_color(color) {
var tmp = "";
if( color.length > 3 && typeof color === "string" ){ // Convert to RGB
for(var x = 0, y = 2;x < color.length; x += 2){
if( x > 0 ) {
tmp += " ";
}
tmp += parseInt( color.substring(x, y + x), 16 );
}
}
else { // Convert to HEX
tmp = color.toString(16);
}
return tmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment