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')
}
thatOneGuy
  • 9,977
  • 7
  • 48
  • 90
Daft
  • 10,277
  • 15
  • 63
  • 105

6 Answers6

65

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'))
Pointy
  • 405,095
  • 59
  • 585
  • 614
14

Try this

if($('#btnDiv').hasClass('rotated')){
   $('#btnDiv').removeClass('rotated')
}else{
  $('#btnDiv').addClass('rotated')
}
Satpal
  • 132,252
  • 13
  • 159
  • 168
3

Just use .toggleClass() to acheive that.

majorhavoc
  • 2,385
  • 1
  • 24
  • 26
2
$("#btnDiv").click(function (){
    $('#slidePanel').toggle( "slide",{direction: 'right'});
    if($('#btnDiv').hasClass('rotated')){
          $('#btnDiv').removeClass('rotated');
    }
    else{
         $('#btnDiv').addClass('rotated');
    }
  });
Aboca
  • 575
  • 2
  • 9
1
if($('#btnDiv').hasClass('rotated')){
   $('#btnDiv').removeClass('rotated')
}else{
   $('#btnDiv').addClass('rotated')
}
Khalid Dabjan
  • 2,697
  • 2
  • 24
  • 35
0

you can you simple swith the class on click


$('.myclassname').on('click', function(){
    $('.myclass h2').toggleClass( 'first_class', 'second_class');
}); 
Mr Coder
  • 507
  • 3
  • 13