Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save firdoussross/5010419 to your computer and use it in GitHub Desktop.
Save firdoussross/5010419 to your computer and use it in GitHub Desktop.
// Experimental : Detect background color brightness and change the font color accordingly
$(".subject-icon").each(function() {
var isBright = (parseInt(get_brightness(rgb2hex($(this).css("background-color")))) > 160);
if (!isBright) $(this).addClass('subject-icon-dark');
});
// Check color brightness
// returns brightness value from 0 to 255
// http://www.webmasterworld.com/forum88/9769.htm
function get_brightness(hexCode) {
// strip off any leading #
hexCode = hexCode.replace('#', '');
var c_r = parseInt(hexCode.substr(0, 2),16);
var c_g = parseInt(hexCode.substr(2, 2),16);
var c_b = parseInt(hexCode.substr(4, 2),16);
return ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000;
}
// convert RGB to hex
// http://stackoverflow.com/questions/1740700/get-hex-value-rather-than-rgb-value-using-jquery
function rgb2hex(rgb) {
if ( rgb.search("rgb") == -1 ) {
return rgb;
} else {
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment