DEV Community

Discussion on: Write a function that outputs a pleasant text color hex given a background color hex

Collapse
 
jessachandler profile image
Jess Chandler • Edited

I wasn't sure what we should do with "pleasant", so I just created little functions to adjust the color

function adjustHex(y) { 
  const x = parseInt(y, 16); 
  if (x<50) {
    return '00';
  } else if(x<=200) {
    return (x-50).toString(16);
  } else {
    return (255).toString(16); 
  }
}

function splitColor(x) { 
  while (x.length <6) { 
    x = '0' + x 
  }; 
  if (x=='000000') {
     return 'ffffff' 
  } else if (x=='ffffff'){
    return '000000'
  } else {
    let y = x.split(/(?=(?:..)*$)/); 
    return adjustHex(y[0])+adjustHex(y[1])+adjustHex(y[2]);
  }
 }

The logic is that if there is an RGB close to FF, then, max that out. If there is one close to 00, then zero that out. If it is in between, lighten it. If the background is black or white, return the opposite.

for example
splitColor('ff00aa') returns "ff0078"
splitColor('ffffff') returns "000000"

There are some edge cases that I did not address - every one that is a combination of extremes. I did not create this in codepen, and now I am kicking myself for just whipping it up in the javascript console while I was debugging something else!