Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing text depending on background.

So I have a page where the color changes dynamically. And so will the text. Here's what I'm using.

if (parseInt(color, 16) > 0xffffff / 2) {}

The problem is that the code isn't applying to 000000, so when I enter that in the hex box, the text stays black, making it unreadable. Here's a demo


1 Answers

isDark method is not giving correct result you can use another function to check color.

var getRGB = function (b) {
  var a;
  if (b && b.constructor == Array && b.length == 3) return b;
  if (a = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b)) return [parseInt(a[1]), parseInt(a[2]), parseInt(a[3])];
  if (a = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b)) return [parseFloat(a[1]) * 2.55, parseFloat(a[2]) * 2.55, parseFloat(a[3]) * 2.55];
  if (a = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b)) return [parseInt(a[1], 16), parseInt(a[2], 16), parseInt(a[3],
16)];
  if (a = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b)) return [parseInt(a[1] + a[1], 16), parseInt(a[2] + a[2], 16), parseInt(a[3] + a[3], 16)];
return (typeof (colors) != "undefined") ? colors[jQuery.trim(b).toLowerCase()] : null
};

var isDark = function (color) {
  var rgb = getRGB(color);
  if (!rgb) return null;
  return (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) > 180 ? false : true;
}

Fiddle Demo

like image 66
Akhlesh Avatar answered Apr 13 '26 09:04

Akhlesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!