Converting an RGB Color To Hex With JavaScript

December 30th, 20094:40 am @ Editor

0


I’ve been distracted by a new jQuery plugin that I’m writing. The plugin has certain situations where it sets various background and foreground colors. You can have it set those styles explicitly or you can have it set a CSS class, and let the CSS stylesheet do the work. I’m writing some unit tests to test the former behavior and ran into an annoying quirk. When testing the color value in IE, I’ll get something like #e0e0e0 , but when testing it in FireFox, I get rgb(224, 224, 224) . Here’s a function I wrote that normalizes colors to the hex format. Thus if the specified color string is already hex, it returns the string. If it’s in rgb format, it converts it to hex. function colorToHex(color) { if (color.substr(0, 1) === '#' ) { return…(read more)