8

I want to change the text color of an element based on the element's background color.

For instance, if the background color is changed to black, then make the text white. If the background color is changed to white, then make the text black.

It'd be a bit more complex than than that though as the user can change the background color to whatever they'd like.

I found some random articles about handling it on the backend, but nothing using javascript (or better yet, jQuery).

Shpigford
  • 24,748
  • 58
  • 163
  • 252
  • Possible duplicate of [Change text color based on brightness of the covered background area?](http://stackoverflow.com/questions/11867545/change-text-color-based-on-brightness-of-the-covered-background-area) – KyleMit May 01 '17 at 14:04

2 Answers2

15

First, create a function that determines whether a color is dark or not (source, modified):

function isDark( color ) {
    var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
    return parseFloat(match[1])
         + parseFloat(match[2])
         + parseFloat(match[3])
           < 3 * 256 / 2; // r+g+b should be less than half of max (3 * 256)
}

Then, use something along the lines of:

$('elem').each(function() {
    $(this).css("color", isDark($(this).css("background-color")) ? 'white' : 'black');
});

http://jsfiddle.net/QkSva/

Peter O.
  • 32,158
  • 14
  • 82
  • 96
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • I had to tweak the math and the matched rgb values had to be converted to integers, but overall it works great! – Shpigford Jul 26 '11 at 19:01
  • 1
    You forgot to convert the matches to int : return parseFloat(match[1]) + parseFloat(match[2]) + parseFloat(match[3]) < (3 * (256 / 2)); Good job, i love this kind of tricks ^^ –  Nov 04 '11 at 16:54
0

I suggest you do use css theming, so change to css file, for that. But you can do it with jQuery.

<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
    $().ready(function () {
        var color = $("body").css("backgroundColor");
        if (color == "...")
            $("body").css("color", "...");
    });
</script>

this is only the simple solution, if you really want to this it would be good to set a event on background changes.

hope that helps

dknaack
  • 60,192
  • 27
  • 155
  • 202