user3058140
user3058140

Reputation:

check and change background color

I want changing background colors, but I can set on red. After red can't work change on blue. If don't return true. I write red - "rgb(256, 0, 0)" and still not work. How can I do?

if($("#row-"+id).css("background-color")!="red")
{
    $("#row-"+id).css("background-color", "red");
}
else if($("#row-"+id).css("background-color")== "red")
{
    alert("don't show this");
    $("#row-"+id).css("background-color", "blue");
}

Upvotes: 0

Views: 1855

Answers (3)

Fabricio
Fabricio

Reputation: 839

Try this:

if($("#row-1").css("background-color")!="rgb(255, 0, 0)")

http://fiddle.jshell.net/vU8r4/

Upvotes: 0

James Hibbard
James Hibbard

Reputation: 17765

In Chrome $(selector).css("background-color") will return an rgb value.

Therefore you can do this:

<p id="row" style="background-color:red">Hello</p>

<script>
  var bgColor = $("#row").css("background-color");

  if(bgColor === "rgb(255, 0, 0)"){
    $("#row").css("background-color", "blue");
  } else {
    $("#row").css("background-color", "red");
  }
</script>

However, this is not jQuery specific. jQuery returns what the browser gives it for the computed value (e.g. from getComputedStyle or currentStyle). What the browser gives it may be in any notation form the browser wants to use.

See here: Why does jQuery .css('background-color') return rgba(0,0,0,0) for 'transparent'?

Upvotes: 0

Ludovic Guillaume
Ludovic Guillaume

Reputation: 3287

Like this :

var $div = $('div');
var bg = $div.css('background-color');

if (bg !== 'rgb(255, 0, 0)') {
    $div.css('background-color', 'red');
}
else {
    $div.css('background-color', 'blue');
}

http://jsfiddle.net/k9jYE/

Upvotes: 1

Related Questions