My rendition:
(function ($) {
$.fn.textInContrast = function () {
var elem = this,
isTransparent;
isTransparent = function (color) {
var match = color.match(/[0-9]+/g);
if (match !== null) {
return !!match[3];
}
else return false;
};
while (isTransparent(elem.css('background-color'))) {
elem = elem.parent();
}
var components = elem.css('background-color').match(/[0-9]+/g);
this.lightBackground = !!Math.round(
(
parseInt(components[0], 10) + // red
parseInt(components[1], 10) + // green
parseInt(components[2], 10) // blue
) / 765 // 255 * 3, so that we avg, then normalize to 1
);
if (this.lightBackground) {
this.css('color', 'black');
} else {
this.css('color', 'white');
}
return this;
};
}(jQuery));
To apply it:
var target = $('#my-element');
target.textInContrast();
This will instantly adjust the text color to black or white as needed. For icons:
if (target.lightBackground) {
iconSuffix = 'black';
} else {
iconSuffix = 'white';
}
Then each icon filename could be like 'save' + iconSuffix + '.jpg'
.
Keep in mind, this won't function when any container exceeds its parent's dimensions (e.g., when CSS height is 0 and overflow isn't hidden). Making it work in those cases would require more intricate solutions.