Skip to content

Instantly share code, notes, and snippets.

@atomiomi
Forked from dcondrey/contrast-color.js
Created June 16, 2020 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atomiomi/e5018c62aba81ee67f18ebbe4a49dc85 to your computer and use it in GitHub Desktop.
Save atomiomi/e5018c62aba81ee67f18ebbe4a49dc85 to your computer and use it in GitHub Desktop.
/**
* Calculate the contrast of a color to determine the appropriate opposing text color.
* @author D. Condrey
* @param {string|object} - element background-color or element
* @return {string}
* white - if background is a dark shade color
* black - if background is a light shade color
*/
define(function() {
'use strict';
var colors = {};
colors.contrast = function(rgb) {
// check if we are receiving an element or element background-color
if (rgb instanceof jQuery) {
// get element background-color
rgb = rgb.css('background-color');
} else if (typeof rgb !== 'string') {
return;
}
// @TODO check for HEX value
// All browsers should return an rgb value so this isn't critical
// Strip everything except the integers eg. "rgb(" and ")" and " "
rgb = rgb.split(/\(([^)]+)\)/)[1].replace(/ /g, '');
// map RGB values to variables
var r = parseInt(rgb.split(',')[0], 10),
g = parseInt(rgb.split(',')[1], 10),
b = parseInt(rgb.split(',')[2], 10),
a;
// if RGBA, map alpha to variable (not currently in use)
if (rgb.split(',')[3] !== null) {
a = parseInt(rgb.split(',')[3], 10);
}
// calculate contrast of color (standard grayscale algorithmic formula)
var contrast = (Math.round(r * 299) + Math.round(g * 587) + Math.round(b * 114)) / 1000;
return (contrast >= 128) ? 'black' : 'white';
};
// Return public interface
return colors;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment