Skip to content

Instantly share code, notes, and snippets.

@NerdyDeedsLLC
Created June 29, 2023 00:47
Show Gist options
  • Save NerdyDeedsLLC/9670a886563d1a24558037952896f052 to your computer and use it in GitHub Desktop.
Save NerdyDeedsLLC/9670a886563d1a24558037952896f052 to your computer and use it in GitHub Desktop.
Lightweight function that will return the appropriate foreground color (white or black) when given a HEX/HEXA background color.
/**
contrastingColor(hex, factorAlpha)
@Description Accepts a HEX/HEXA color in any valid format (#HEX/#HEXA/#HHEEXX/#HHEEXXAA;
'#' is optional), and a boolean indicating if its opacity should be
considered and returns either '#000' or '#FFF' representing the preferred
foreground color for text atop it.
@param <STRING> hex any valid hex color code.
@param <BOOLEAN> factorAlpha whether or opacity should be considered (DEFAULT: false)
@returns <STRING> returns hex color code for white or black (#FFF/#000)
*/
function contrastingColor(hex, factorAlpha=false) {
let [r,g,b,a]=hex.replace(/^#?(?:(?:(..)(..)(..)(..)?)|(?:(.)(.)(.)(.)?))$/, '$1$5$5$2$6$6$3$7$7$4$8$8').match(/(..)/g).map(rgb=>parseInt('0x'+rgb));
return ((~~(r*299) + ~~(g*587) + ~~(b*114))/1000) >= 128 || (!!(~(128/a) + 1) && factorAlpha) ? '#000' : '#FFF';
}
@NerdyDeedsLLC
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment