BGCodes
BGCodes

Reputation: 99

How do I toggle color attributes in jquery?

I'm trying to toggle the color of a button every time it's clicked. I'm able change the color initially, but not able to change it back.

$("#greenCirc").click(function(){
    if($("#greenCirc").css("background-color", "green")){
        $("#greenCirc").css("background-color", "yellow");
    }   
    else{
        $("#greenCirc").css("background-color", "green");
    };
});

Upvotes: 0

Views: 307

Answers (2)

Jason McFarlane
Jason McFarlane

Reputation: 2175

You can do this way easier with jQuery toggleClass

$( "button" ).click(function() {
  $( this ).toggleClass( "toggled" );
});
button {
  background: green;
}

button.toggled {
  background: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Button</button>

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 371168

Use .css("background-color") - with one parameter - to retrieve the current color value. But, note that this will give you an RGB string like rgb(0, 128, 0) instead of green. Compare against that:

$("#greenCirc").click(function() {
  if ($("#greenCirc").css("background-color") === "rgb(0, 128, 0)") {
    $("#greenCirc").css("background-color", "yellow");
  } else {
    $("#greenCirc").css("background-color", "green");
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="greenCirc">click</div>

But I would much prefer using a class instead:

$("#greenCirc").click(function() {
  this.classList.toggle('on');
});
#greenCirc {
  background-color: yellow;
}
#greenCirc.on {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="greenCirc">click</div>

Upvotes: 4

Related Questions