Managing text contrast with an AngularJS Directive

Sometimes you need to set background colors dynamically. And if you are setting text over the top you have a real problem, because you need to set text color dynamically as well. Black text just isn’t readable on deep purple.

One way to go about this is to calculate the brightness from the RGB color. According to Themergency , the formula for this looks something like:

 Math.sqrt((0.299 * R * R) + (0.587 * G * G) + (0.114 * B * B))

A value of 128 is about a 50% brightness, give or take.

For more details on implementation, including jQuery and PHP solutions, the Themergency link is pretty useful. But if you’re inclined in an AngularJS direction, I wrote a little proof-of-concept directive below that should get you started.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>