Skip to content

Instantly share code, notes, and snippets.

@veganben
Last active August 29, 2015 14:10
Show Gist options
  • Save veganben/1fd5e1b8743320ea30a0 to your computer and use it in GitHub Desktop.
Save veganben/1fd5e1b8743320ea30a0 to your computer and use it in GitHub Desktop.
Get a contrasting colour. Put a black label on a light background, a white label on a light one. For example.
/**
* @param hex {String} hex colour with or without hash
* @returns {String} black if the original colour was light, white if it was dark. With hash if it had it in the first place.
*/
getContrastMonochrome = function (hex) {
var colour = hex,
sum,
hasHash = false;
hex = hex.charAt(0) === "#" ? hasHash = hex.substring(1) : hex;
sum = (function(h){
var sum = 0;
for(var i = 0; i < h.length; i+=2){
sum += parseInt(h.substr(i,2),16);
}
return sum;
})(hex);
// yeah yeah, magic number
// you can replace it with
// (parseInt("ff", 16) * 3) / 2
// if you really want
colour = sum > 382 ? "000000" : "ffffff";
if(hasHash) {
colour = "#" + colour;
}
return colour;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment