Add and remove class on switch

I am trying to switch between colors using .js. I want the color to be red when I close the panel and then change the color to black when I open the panel. Script 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");
  });
});

      

+3


source to share


1 answer


Plain:

Change addClass("red")

to toggleClass("red")

for example:

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

      

Updated violin

Defensive:



An approach like this is probably better:

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

      

What it means: It doesn't just toggle the state, but sets it according to the panel's visibility. Moreover, it uses a callback from the slideToggle method to toggle the "red" class after the animation finishes, so you will definitely get the correct state of the panel.

This should go well, but sometimes it is weird that when the element is clicked fast. This method ensures that the invalid state is automatically self-healing, so it's a little more protective.

Updated script (2)

+5


source







All Articles