I am trying to check for the background of an element, here is my code. But it doesn\'t work:
I tried two ways, here is the first:
function changeCol
As @undefined already said, css()
will return an rgb
value for the background-color, which solves your problem, so you should upvote his answer. However, I strongly advise you against having fixed colors in your JavaScript.
An alternative is to define two CSS classes, which are the appropriate place to put styles:
.orange {
background-color: #ffb100;
}
.white {
background-color: white;
}
And then simply toggle the field's class, which is much cleaner than to compare hex or rgb values in your JavaScript, and easier to switch when you want a different color:
function changeColor(field) {
field.toggleClass("white orange");
}
Here's a DEMO.
I'm not sure what field
is referring to, but my guess stands that it is the id of the element?
If so, try wrapping field
like so $('#' + field).css
.
NOTE: Here's a VERY NICE function for converting HEX to RGB
function hexToRgb(string)
{
if(!string || typeof string !== 'string') return false;
if(
string.substring(0,1) == '#' &&
(string.length == 4 || string.length == 7) &&
/^[0-9a-fA-F]+$/.test(string.substring(1, string.length))
){
string = string.substring(1, string.length);
if(string.length == 3)
string = string[0] + string[0] + string[1] + string[1] + string[2] + string[2];
return 'rgb(' +
parseInt(string[0] + string[1], 16).toString() + ',' +
parseInt(string[2] + string[3], 16).toString() + ',' +
parseInt(string[4] + string[5], 16).toString() +
')';
}
else return false;
}
From jQuery .css() documentation:
Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as
em
,ex
,px
or%
in a style sheet. Different browsers may return CSS color values that are logically but not textually equal, e.g.,#FFF
,#ffffff
, andrgb(255,255,255)
.
Most browsers return a rgb
value, so you can code:
if (field.css('background-color') === 'rgb(255, 177, 0)') {
// ...
}
The above snippet, based on the specified reason, may fail in some browsers. You can consider using a color conversion library or create a temporary element and set and get it's background-color
/color
property.
A simple jQuery plugin:
(function($) {
$.fn.isBgColor = function(color) {
var thisBgColor = this.eq(0).css('backgroundColor');
var computedColor = $('<div/>').css({
backgroundColor: color
}).css('backgroundColor');
return thisBgColor === computedColor;
}
})(jQuery);
Usage:
if ( field.isBgColor('#ffb100') ) {
// ...
}