Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeClass() if it exists

Tags:

html

jquery

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') } 
like image 963
Daft Avatar asked Aug 27 '13 14:08

Daft


People also ask

How do you check class is exists in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

What is the use of removeClass?

The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.

How can I replace one class with another in jQuery?

To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.


2 Answers

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')) 
like image 187
Pointy Avatar answered Oct 08 '22 04:10

Pointy


Try this

if($('#btnDiv').hasClass('rotated')){    $('#btnDiv').removeClass('rotated') }else{   $('#btnDiv').addClass('rotated') } 
like image 38
Satpal Avatar answered Oct 08 '22 04:10

Satpal