user3880297
user3880297

Reputation: 13

CSS-property 'background' not working in 'if.. else'

I can not make CSS-property 'background' work when using it in an 'if.. else' - statement. I tried all possible combinations of 'background-color' and backgroundColor' in both CSS and JQuery, but nothing is working.

The funny thing is that when exchanging the 'if..' with another property fx ('width') == '500px' everything is working fine.

Are there any special thing i should know when using 'background'? Heres the code that doesn't work - the div turns yellow when clicking even thought it should become pink..

.box {  
    width: 500px;
    height: 200px;
    background: red;
}

<script src='http://code.jquery.com/jquery-latest.min.js'></script>
<script>
$(document).ready(function() {      
    $('.box').click(function(){
        if ($('.box').css('background') == 'red') {
            $('.box').css('background', 'pink'); 
        }  
        else {  
            $('.box').css('background', 'yellow');
        } 
    });
});
</script>

ANSWER - this is the original answer from showdev, which i think reflects my question better - could be a help to future visitors:

  $('.box').click(function() {
    if ($(this).css('background-color') == 'rgb(255, 0, 0)') {
      $(this).css('background-color', 'pink');
    } else {
      $(this).css('background-color', 'yellow');
    }
  });

Upvotes: 1

Views: 182

Answers (1)

showdev
showdev

Reputation: 29178

The CSS background is shorthand for several individual background properties including background-clip, background-color, background-image, background-origin, background-position, background-repeat, background-size, and background-attachment.

As a result, the value of background is returned as something like rgb(255, 192, 203) none repeat scroll 0% 0% / auto padding-box border-box.

You can use background-color instead, but jQuery returns background-color values in RGB rather than HEX. So you'll need to match RGB values rather than HEX or words ("red").

Also, I changed references inside your click handler to use $(this) rather than selecting the box again. This allows more flexibility when multiple boxes are on the page.

$(document).ready(function() {
  $('.box').click(function() {
    $this = $(this);
    $this.css('background-color',
        $this.css('background-color') == 'rgb(255, 0, 0)' ? 'pink' : 'yellow');
  });
});
.box {
  width: 500px;
  height: 50px;
  background-color: red;
}
.box.blue {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box blue"></div>

Regarding CSS colors as RGB:

  1. "Computed Value: If the value is translucent, the computed value will be the rgba() corresponding one. If it isn't, it will be the rgb() corresponding one." -Color - CSS | MDN

  2. Can I force backgroundColor [to return in] hexadecimal format?

Upvotes: 1

Related Questions