Textlight by Background

Change text color based on background color

by Kevin Pliester

HTML

<div style="background-color: red">red</div>
<div style="background-color: purple">purple</div>
<div style="background-color: blue">blue</div>
<div style="background-color: green">green</div>
<div style="background-color: yellow">yellow</div>
<div style="background-color: orange">orange</div>
<div style="background-color: #454545">orange</div>

JavaScript

$(document).ready(function() {

  var base = 'div'; // Change it to your element

  $(base).each(function() {

    var target = $(this);

    var bgcolor = target.css('background-color');
    var rgb = bgcolor.replace('rgb(', '').replace(')', '').split(',');

    var c = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';

    var o = Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) + (parseInt(rgb[2]) * 114)) / 1000);

    if (o > 125) {
      $(target).css('color', 'black');
    } else {
      $(target).css('color', 'white');
    }

    $(target).css('background-color', c);

    var r = Math.round(Math.random() * 255);
    var g = Math.round(Math.random() * 255);
    var b = Math.round(Math.random() * 255);

    rgb[0] = r;
    rgb[1] = g;
    rgb[2] = b;

  });
});