Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two color values in jQuery/JavaScript?

Tags:

I get color value with jQuery with .css('color'), and then I know color that it should be.

How can I compare color value that I get from jQuery with for example black color value?

like image 248
newbie Avatar asked Mar 04 '10 08:03

newbie


People also ask

How do you compare two colors?

The most common method would be a visual color comparison by looking at two physical color samples side by side under a light source. Color is very relative, so you can compare colors in terms of the other color across dimensions such as hue, lightness and saturation (brightness).

How can check background color in jquery?

click(function() { var color = $( this ). css( "background-color" ); $( "p" ). html( "That div is " + color + "." ); });


1 Answers

Here is an approach that should work on all browsers using JQuery:

  1. Create a hidden div <div id="dummy" style="display:none;"></div> on your HTML page. (Creating the dummy element dynamically with JQuery does not work for named colors)
  2. Set the color of the dummy element to the expected color, i.e. $('#dummy').css('color','black');
  3. Compare the color of the dummy element with the element you want to check

i.e.

if($('#element').css('color') === $('#dummy').css('color')) {
  //do something
}
like image 91
Mike Avatar answered Oct 14 '22 15:10

Mike