6

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');
                }
            }
eatonphil
  • 13,115
  • 27
  • 76
  • 133
  • how styles are added inline or in the external stylesheet-file? It's important – d.k Aug 25 '12 at 18:15
  • external stylesheet, but it is undefined at the beginning of the page. it turns to the reddish color once a form is submitted and fields are blank. – eatonphil Aug 25 '12 at 18:16
  • 1
    What is `field`? The first obviously cannot work, since `.css('background-color','#ffb100')` **sets** the `background-color` to `#ffb100` and returns the jQuery object. – Felix Kling Aug 25 '12 at 18:16
  • try to print the value of the background-color to see in which format you get it (#FFB100 , or #ffb100 or ffb100...) – RedhopIT Aug 25 '12 at 18:16
  • 1
    You should consider solving the problem by [toggling a class](http://api.jquery.com/toggleClass/) instead of what you're currently doing. e.g. `function changeColor (field) { field.toggleClass('foo'); }`. Have your stylesheet define the colors that `.foo` (and not `.foo`) should use. – Rob Hruska Aug 25 '12 at 18:19
  • Here's a [fiddle with a toggling example](http://jsfiddle.net/PnhQJ/) - see if it fits what you're trying to do. It uses a `click` handler, but you could use the same concept anywhere. – Rob Hruska Aug 25 '12 at 18:47

4 Answers4

17

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') ) {
   // ...
}
Ram
  • 143,282
  • 16
  • 168
  • 197
  • is there no way to have it equal to my hex value? or is there a jquery convert keyword? – eatonphil Aug 25 '12 at 18:21
  • @phileaton You could try [this](http://stackoverflow.com/questions/1740700/get-hex-value-rather-than-rgb-value-using-jquery). – Cat Aug 25 '12 at 18:22
  • 1
    @phileaton unfortunately no, but you can write a function that converts the hex value to a rgb value. – Ram Aug 25 '12 at 18:23
  • 1
    Note that the spaces in 'rgb(255, 177, 0)' matter, it took me half an hour to figure that out. – Kevin May 12 '13 at 12:48
5

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.

João Silva
  • 89,303
  • 29
  • 152
  • 158
1

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;
}
Jordan Richards
  • 532
  • 3
  • 18
0

Important: make sure you type rgb(128, 128, 128) with one blank space after the commas. If you type rgb(128,128, 128) it won't work. It's space sensitive.

Try it: alert(element.css('background-color') === 'rgb(128, 128, 128)')

Answering the main question:

var style = 'background-color';
var gray = 'rgb(128, 128, 128)';

if(element.css(style) === gray){
  element.css(style,'blue');
}else{
  element.css(style,gray);
}
Gass
  • 7,536
  • 3
  • 37
  • 41