Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Auto Text Color Detector
// Converts color code to RGB
//====================================
function colorCodeToRGB(colorCode){
var c;
var rgbaValidation = (/([R][G][B][A]?[(]\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])(\s*,\s*((0\.[0-9]{1})|(1\.0)|(1)))?[)])/i.test(colorCode)) ;
var hexValidation = (/^#([A-Fa-f0-9]{3}){1,2}$/.test(colorCode));
if(hexValidation){
c= colorCode.substring(1).split('');
if(c.length== 3){
c= [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c= '0x'+c.join('');
return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')';
}else if(rgbaValidation){
return colorCode;
}
return colorCode;
}
// Detects text color based on given color
//=====================================
function autoTextColor(bgColor, lightColor, darkColor){
var lightTextColor = (typeof lightColor === "string")? lightColor : "#fff";
var darkTextColor = (typeof darkColor === "string")? darkColor : "#333";
var rgbString = colorCodeToRGB(bgColor);
var matchColors = /rgb\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\)/;
var rgb = matchColors.exec(rgbString);
if (rgb === null) {
return;
}
var o = Math.round(((parseInt(rgb[1]) * 299) +
(parseInt(rgb[2]) * 587) +
(parseInt(rgb[3]) * 114)) / 1000);
return (o > 125) ? darkTextColor : lightTextColor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.