Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Change text color based on containing element's background color?

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).

like image 286
Shpigford Avatar asked Jul 19 '11 16:07

Shpigford


People also ask

How can I change the text color with JQuery?

To change the text color with jQuery, use the jQuery css() method. The color css property is used to change text color.

How do you change the text color of an element in JavaScript?

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.

How can set background color in JQuery?

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.


1 Answers

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/

like image 164
pimvdb Avatar answered Nov 15 '22 22:11

pimvdb