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).
To change the text color with jQuery, use the jQuery css() method. The color css property is used to change text color.
Use the String fontcolor() Method We can apply the fontcolor() method on any text string, and it returns the <font> HTML element with the color attribute.
To add the background color, we use css() method. The css() method in JQuery is used to change style property of the selected element. The css() in JQuery can be used in different ways. The css() method can be used to check the present value of the property for the selected element.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With