MrRobot9
MrRobot9

Reputation: 2684

jquery: check the current toggled class

So, this is my code

     $(".heart.fa").click(function() {
          $(this).toggleClass("fa-heart fa-heart-o");

//Wanna check here is its fa-heart or fa-heart-o

           var row = $(this).closest("i");
           var rowId = row.attr("id");
            alert(rowId);

        });

<div>
  <i id= '".$i."' class='heart fa fa-heart-o'></i>
</div>

Want to check inside this function if it's currently fa-heart-o or fa-heart

Upvotes: 2

Views: 52

Answers (3)

nemanja
nemanja

Reputation: 694

Shorter syntax with ternary operator and one major change:

$(".heart.fa").click(function(e) {
    $(e.target).toggleClass("fa-heart fa-heart-o");

    $(e.target).hasClass("fa-heart-o") ? console.log("It was fa-heart-o") : console.log("It was fa-heart");
});

I am using e.target instead of this. Better safe than sorry. You can read about the differences here.

Upvotes: 1

soccer7
soccer7

Reputation: 4015

Try this-

$(this).toggleClass("fa-heart fa-heart-o");

if($(this).hasClass('fa-heart') && !$(this).hasClass('fa-heart-o')){
  console.log('class is fa-heart');
} else if($(this).hasClass('fa-heart-o') && !$(this).hasClass('fa-heart')){
  console.log('class is fa-heart-o');
}

Upvotes: 1

David
David

Reputation: 415

The hasClass function is probably what you want https://api.jquery.com/hasclass/

So you would do something like:

if($(this).hasClass('fa-heart-o')){
//logic for having fa-heart-o
}
else{
//logic for having fa-heart
}

Upvotes: 2

Related Questions