How do I invert the text-color of an element using jQuery?
<div style="color: rgb(0, 0, 0)">Invert me</div>
How do I invert the text-color of an element using jQuery?
<div style="color: rgb(0, 0, 0)">Invert me</div>
A bit late but better late than never:
function invert(rgb) {
rgb = Array.prototype.join.call(arguments).match(/(-?[0-9\.]+)/g);
for (var i = 0; i < rgb.length; i++) {
rgb[i] = (i === 3 ? 1 : 255) - rgb[i];
}
return rgb;
}
console.log(
invert('rgba(255, 0, 0, 0.3)'), // 0, 255, 255, 0.7
invert('rgb(255, 0, 0)'), // 0, 255, 255
invert('255, 0, 0'), // 0, 255, 255
invert(255, 0, 0) // 0, 255, 255
);
First load http://www.phpied.com/files/rgbcolor/rgbcolor.js
Then you can do
$.fn.invertElement = function() {
var prop = 'color';
if (!this.css(prop)) return;
var color = new RGBColor(this.css(prop));
if (color.ok) {
this.css(prop, 'rgb(' + (255 - color.r) + ',' + (255 - color.g) + ',' + (255 - color.b) + ')');
}
};
$('div').invertElement();
This should also work when the color property is specified with a word (like "black") rather than an RGB value. It won't work well with transparency, however.
I found a great 'Hexadecimal Color Inverter' function wrote by Matt LaGrandeur (http://www.mattlag.com/)
function invertHex(hexnum){
if(hexnum.length != 6) {
console.error("Hex color must be six hex numbers in length.");
return false;
}
hexnum = hexnum.toUpperCase();
var splitnum = hexnum.split("");
var resultnum = "";
var simplenum = "FEDCBA9876".split("");
var complexnum = new Array();
complexnum.A = "5";
complexnum.B = "4";
complexnum.C = "3";
complexnum.D = "2";
complexnum.E = "1";
complexnum.F = "0";
for(i=0; i<6; i++){
if(!isNaN(splitnum[i])) {
resultnum += simplenum[splitnum[i]];
} else if(complexnum[splitnum[i]]){
resultnum += complexnum[splitnum[i]];
} else {
console.error("Hex colors must only include hex numbers 0-9, and A-F");
return false;
}
}
return resultnum;
}
Source is here: http://www.mattlag.com/scripting/hexcolorinverter.php