jquery if background color ==
jquery
Solution
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`, and `rgb(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') ) {
// ...
}
Problem
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 changeColor(field) { if(field.css('background-color','#ffb100')) { field.css('background-color','white'); } else { field.css('background-color','ffb100'); } } ``` here is the second: ``` function changeColor(field) { if(field.css('background-color') === '#ffb100') { field.css('background-color','white'); } else { field.css('background-color','ffb100'); } } ``` But neither worked! Any suggestions? EDIT: This is my latest code, but it still is not working: ``` function changeColor(field) { if(field.css('background-color') == 'rgb(255, 255, 255)') { field.css('background-color','ffb100'); } else { field.css('background-color','white'); } } ```