Created
November 24, 2015 20:57
-
-
Save AdrianoCahete/c8ae2590eb4a4a5512bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Find if a background is dark or light and define text color. | |
* Created by Adriano Caheté <https://github.com/AdrianoCahete> | |
*/ | |
$(document).ready(function () { | |
function isDark(color) { | |
var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color); | |
var r = parseInt(match[1]); | |
var g = parseInt(match[2]); | |
var b = parseInt(match[3]); | |
var yiq = (r * 299 + g * 587 + b * 114) / 1000; | |
return (yiq <= 128); | |
} | |
var divs = $(".color-item"); | |
$(divs).each(function () { | |
$(this).css("color", isDark($(this).css("background-color")) ? 'white' : 'black'); | |
}); | |
}); | |
In HTML: | |
<div class="color-item" style="background-color:#3C3C3C;">#3C3C3C</div> | |
<div class="color-item" style="background-color:#FFFFFF;">#FFFFFF</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment