Last active
February 23, 2016 01:55
-
-
Save tsprates/4814a6838b52a60509e1 to your computer and use it in GitHub Desktop.
Converts a color name to its corresponding hex string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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