Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change text colour based on dynamically changing background colour

I am setting up a new website and need my text to change colour based on the ever-changing background colours in order to maintain contrast. I have scoured the web for answers that don't involve Sass, but none have worked...

I have tried some JavaScript, but they work only when the background is a fixed colour that you change manually.

My Current File: https://codepen.io/jonathanlee/pen/wZXvRY

var color = function getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
setInterval(function() {
  document.getElementById("test").style.backgroundColor = color(); //() to execute the function!
}, 3000);

var ww = function isDarkColor(rgb) {
  return Math.round((
    parseInt(rgb[0], 10) * 299 +
    parseInt(rgb[1], 10) * 587 +
    parseInt(rgb[2], 10) * 114) / 1000) <= 140
}

if (ww <= 140) {
  document.getElementById("test").style.color = '#fff';
} else {
  document.getElementById("test").style.color = '#000';
}

One of the other solutions I've tried, but didn't work: http://jsfiddle.net/QkSva/

function isDark(color) {
  var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
  return (match[1] & 255) +
    (match[2] & 255) +
    (match[3] & 255) <
    3 * 256 / 2;
}
$('div').each(function() {
  console.log($(this).css("background-color"))
  $(this).css("color", isDark($(this).css("background-color")) ? 'white' : 'black');
});

The real-life example is an alternate homepage on the website I'm working on, https://nepmelbourne.com/q. I have got a dynamic background, but there are some colours that don't contrast well against my white text.

like image 407
Jonathan Lee Avatar asked Apr 20 '19 09:04

Jonathan Lee


People also ask

How do you change the color of text in dynamics?

TextView Text Color – To change the color of text in TextView, you can set the color in layout XML file using textColor attribute or change the color dynamically in Kotlin file using setTextColor() method.


1 Answers

One way to do it would be to set opposite color of background color to text as follows,

function invertColor(hex, bw) {
    if (hex.indexOf('#') === 0) {
      hex = hex.slice(1);
    }
    // convert 3-digit hex to 6-digits.
    if (hex.length === 3) {
      hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
    }
    if (hex.length !== 6) {
      throw new Error('Invalid HEX color.');
    }
    var r = parseInt(hex.slice(0, 2), 16),
      g = parseInt(hex.slice(2, 4), 16),
      b = parseInt(hex.slice(4, 6), 16);
    if (bw) {
      // http://stackoverflow.com/a/3943023/112731
      return (r * 0.299 + g * 0.587 + b * 0.114) > 186 ?
        '#000000' :
        '#FFFFFF';
    }
    // invert color components
    r = (255 - r).toString(16);
    g = (255 - g).toString(16);
    b = (255 - b).toString(16);
    // pad each with zeros and return
    return "#" + padZero(r) + padZero(g) + padZero(b);
  }

  function padZero(str, len) {
    len = len || 2;
    var zeros = new Array(len).join('0');
    return (zeros + str).slice(-len);
  }

  var color = function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }

  setInterval(function() {
    var bgColor = color();
    var textColor = invertColor(bgColor,true);
    document.getElementById("test").style.backgroundColor = bgColor; //() to execute the function!
    document.getElementById("test").style.color = textColor;
  }, 3000);
<div id="test">This is some text</div>

Opposite color code taken from How can I generate the opposite color according to current color?

Added an extra parameter bw to invertColor(), if bw is set to true the text color will be black if background is bright and vice versa.

like image 142
Shoyeb Sheikh Avatar answered Oct 02 '22 14:10

Shoyeb Sheikh