Ghostff
Ghostff

Reputation: 1458

Adding and removing class on toggle

Am trying to toggle between colors using .js. i want the color to be red when i close the panel, then change to black when i open the panel. Fiddle Here

HTML

<div class="flip">Click to slide the panel down or up</div>
<div class="panel">Hello world!</div>

CSS

.flip{ color: back; }
.panel,.flip {
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
.panel{ padding:50px; }
.red{ color: red; }

JS

$(document).ready(function(){
  $(".flip").click(function(){
    $(".panel").slideToggle("slow");
       $(".flip").addClass("red");
  });
});

Upvotes: 3

Views: 86

Answers (1)

GolezTrol
GolezTrol

Reputation: 116160

Simple:

Change addClass("red") to toggleClass("red"), like so:

$(document).ready(function(){
  $(".flip").click(function(){
    $(".panel").slideToggle("slow");
    $(".flip").toggleClass("red");
  });
});

Updated fiddle

Defensive:

Arguably better is this approach:

$(document).ready(function(){
  $(".flip").click(function(){
      $(".panel").slideToggle("slow", function(){
          $(".flip").toggleClass("red", $(".panel").is(":hidden"));
      });
  });
});

What this does: it doesn't just toggle the state, but it sets it according to the visibility of the panel. Moreover, it uses a callback from slideToggle to toggle the 'red' class after the animation is done, so you are sure to have the right state of the panel.

It should go well, but sometimes weird things can happen when an element is clicked in quick succession. This method makes sure that an invalid state repairs itself automatically, so it's a bit more defensive.

Updated fiddle (2)

Upvotes: 5

Related Questions