Search code examples
javascriptjqueryclasstoggle

Can I use a condition inside a toggleClass based on the toggle status


I am creating a toggle and need to execute a command based on the toggle status.

When I click .flip1 first time it adds the flipped class to .card1. I also want it to show an alert "flipped added"

When I click it again it removes the flipped class and I want it to show an alert "flipped removed".

I imagine that the code will look something like this:

$(document).ready(function () {

    $('.flip1').click(function () {

        $('.card1').toggleClass('flipped');

          if ("class added"){
            alert("flipped added");
          }
          if ("class removed"){
            alert("flipped removed");  
          }
        });
});

Is there something I can put in the if to know whether the toggle is true or false?


Solution

  • This can be achieved via jQuery's hasClass() method like so:

    $(document).ready(function() {
      $('.flip1').click(function() {
    
          $('.card1').toggleClass('flipped');
    
          // use hasClass to see if .card1 has .flipped class now applied.
          // if true, that indicates it was just added
          if ($('.card1').hasClass('flipped')) {
            alert("flipped added");
          } else {
            alert("flipped removed");
          }
        }
      );
    });
    .flipped {
    background:yellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    
    <div class="card1">
    Card1 (yellow if flipped)
    </div>
    
    <a href="#" class="flip1">
    Flip1
    </a>