JQuery: change text color based on element background color?

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

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

It will be a little more complicated than if the user could change the background color to whatever he wants.

I found some random articles about handling it on the server , but didn't use javascript (or better yet, jQuery).

+7
source share
2 answers

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

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/

+12
source

I suggest you use the css theme, so for this you need to go to the css file. 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 just a simple solution, if you really want it, it would be nice to set the event in the background.

hope that helps

0
source

All Articles