Skip to content

Instantly share code, notes, and snippets.

@tsprates
Last active February 23, 2016 01:55
Show Gist options
  • Save tsprates/4814a6838b52a60509e1 to your computer and use it in GitHub Desktop.
Save tsprates/4814a6838b52a60509e1 to your computer and use it in GitHub Desktop.
Converts a color name to its corresponding hex string.
/**
* Converts a color name to its corresponding hex string.
*
* @example getHexColor('orange') == '#ffa500'
* @param {String} colorValue The color name.
* @return {String}
*/
var getColorNameFromHexColor = (function() {
var elem = document.createElement('div');
var bg;
function hex(x) {
return ('0' + parseInt(x).toString(16)).slice(-2);
}
return function(colorValue) {
elem.style.backgroundColor = colorValue;
if (elem.currentStyle) {
bg = elem.currentStyle["backgroundColor"];
} else if (window.getComputedStyle) {
bg = document.defaultView.getComputedStyle(elem, null).getPropertyValue("background-color");
}
if (parseInt(bg.search('rgb'), 10) === -1) {
return bg;
} else {
bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return '#' + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment