Adding flexibility to our contrast checker function
Brian’s function only accepts six-character hexcolors, and they cannot have a leading hash (#).
Let’s first modify it to accept a leading hash. We’ll use Array.slice() to get the first character and check if it equals #. If it does, we’ll use Array.slice() again to remove the leading hash and redefine hexcolor.
Next, let’s modify the function to allow both three and six-character colors.
To do that, we’ll first check the length of hexcolor. If it’s 3, we’ll use Array.split() to convert the hexcolor string into an array of characters. Then, we’ll use Array.map() to double each character, and Array.join() to combine it back into a string.
/*!
* Get the contrasting color for any hex color
* (c) 2019 Chris Ferdinandi, MIT License, https://gomakethings.com
* Derived from work by Brian Suda, https://24ways.org/2010/calculating-color-contrast/
* @param {String} A hexcolor value
* @return {String} The contrasting color (black or white)
*/
var getContrast = function (hexcolor){
// If a leading # is provided, remove it
if (hexcolor.slice(0, 1) === '#') {
hexcolor = hexcolor.slice(1);
}
// If a three-character hexcode, make six-character
if (hexcolor.length === 3) {
hexcolor = hexcolor.split('').map(function (hex) {
return hex + hex;
}).join('');
}
// Convert to RGB value
var r = parseInt(hexcolor.substr(0,2),16);
var g = parseInt(hexcolor.substr(2,2),16);
var b = parseInt(hexcolor.substr(4,2),16);
// Get YIQ ratio
var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
// Check contrast
return (yiq >= 128) ? 'black' : 'white';
};
Here’s a demo on CodePen