removeClass() if it exists
Asked Answered
S

7

33

This function adds a rotated class to my button when I click it. The button has an arrow on it which points in the direction the panel has slid.

How could I remove the rotated class when I click the button again?

$("#btnDiv").click(function (){
     $('#slidePanel').toggle( "slide",{direction: 'right'});
     $('#btnDiv').addClass('rotated');
});

Something like this maybe?

if('rotated'){
    removeClass('rotated')
}else{
    addClass('rotated')
}
Sorrento answered 27/8, 2013 at 14:24 Comment(0)
L
67

You can use .toggleClass()

$('#btnDiv').toggleClass('rotated');

That adds it if it's missing, and removes it if it's present. There's also .is() to check for things like that:

if ($('#btnDiv').is('.rotated'))

or more simply:

if ($('#btnDiv').hasClass('rotated'))
Lightfingered answered 27/8, 2013 at 14:25 Comment(7)
...and if you ever need to check if a class is set: hasClass() : api.jquery.com/hasClassDecapod
Excellent! What a quick fix! Cheers Pointy!Sorrento
@Virus721 there's no need to check if all you want to do is add the class; .addClass() won't add it twice.Lightfingered
Okay, so this question has no reason to be then.Bergerac
@Bergerac I'm pretty sure that the OP wants to remove the class if it's present, and add the class if it's missing.Lightfingered
I appreciate the suggestion Virus, but Pointy's worked perfectly for me.Sorrento
Thanks, this helped with this: $(this).toggleClass('selectedTrack_row').siblings().removeClass('xyzClass');Talky
C
15

Try this

if($('#btnDiv').hasClass('rotated')){
   $('#btnDiv').removeClass('rotated')
}else{
  $('#btnDiv').addClass('rotated')
}
Coit answered 27/8, 2013 at 14:25 Comment(0)
B
3

Just use .toggleClass() to acheive that.

Byelorussian answered 27/8, 2013 at 14:25 Comment(0)
E
2
$("#btnDiv").click(function (){
    $('#slidePanel').toggle( "slide",{direction: 'right'});
    if($('#btnDiv').hasClass('rotated')){
          $('#btnDiv').removeClass('rotated');
    }
    else{
         $('#btnDiv').addClass('rotated');
    }
  });
Eclogue answered 27/8, 2013 at 14:27 Comment(0)
F
1
if($('#btnDiv').hasClass('rotated')){
   $('#btnDiv').removeClass('rotated')
}else{
   $('#btnDiv').addClass('rotated')
}
Flita answered 27/8, 2013 at 14:27 Comment(0)
P
0

you can you simple swith the class on click


$('.myclassname').on('click', function(){
    $('.myclass h2').toggleClass( 'first_class', 'second_class');
}); 
Perot answered 2/9, 2020 at 11:7 Comment(0)
O
0

You can pass boolean value, as second arg, if the driver of adding or removing a class is based on some true/false.

some.prototype.setSomeMode = function(enabled){
    $('#btnDiv').toggleClass('theclassToAddOrRemove', this.refreshingStopped); 
}
Observer answered 25/7 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.