David Knaack
David Knaack

Reputation: 172

Invert text-color of a specific element (using jQuery)

How do I invert the text-color of an element using jQuery?

<div style="color: rgb(0, 0, 0)">Invert me</div>

Upvotes: 4

Views: 34100

Answers (4)

General Grievance
General Grievance

Reputation: 4988

For newer browsers (>2016), there is no need to do any extra calculations thanks to the CSS filter property. Setting the value to invert(1) will invert the foreground color.

MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/filter#invert

$('#invert-me').css({ filter: 'invert(1)' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="invert-me" style="color: rgb(0, 255, 0);">Invert me (Opposite of green is magenta)</div>

Upvotes: 1

yckart
yckart

Reputation: 33408

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
);

Upvotes: 11

Ofer Segev
Ofer Segev

Reputation: 5282

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

Upvotes: 1

Muhd
Muhd

Reputation: 25586

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.

Upvotes: 1

Related Questions