mhmdrupal
mhmdrupal

Reputation: 165

onclick addClass, how to remove class again

I've got this piece of code to toggle a side panel:

$(".example_wrapper_panel_link").click(function() { 
$(".example_wrapper").addClass('example_wrapper_active'); 
$(".example_wrapper_panel").animate({width: "toggle"}, 400);

The addClass is working fine, but now when I click again to hide the div, I want to remove the added class again.

Can't seem to find the solution for this case.

Thanks in advance for your help.

Upvotes: 2

Views: 1204

Answers (5)

The System Restart
The System Restart

Reputation: 2881

You should go for .toggleClass() instead of .addClass() and .removeClass().

Upvotes: 0

root
root

Reputation: 1583

try using .toggleClass.

$(".example_wrapper").toggleClass('example_wrapper_active');

Upvotes: 1

Jeff Watkins
Jeff Watkins

Reputation: 6359

.removeClass('class'); should do it, see the jQuery API here. If you're interested in alternating, .toggleClass('class'); may be more appropriate.

Upvotes: 1

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14877

.removeClass() removes a given class.

.toggleClass() toggles a given class, which means that it'll add that class if missing, otherwise it will remove it.

So your handler may become as simple as:

$(".example_wrapper").toggleClass('example_wrapper_active'); 

Documentation for removeClass() and for toggleClass()

Upvotes: 2

thecodeparadox
thecodeparadox

Reputation: 87073

You should use .toggleClass() method.

$(".example_wrapper_panel_link").click(function() { 
   // instead of addClass() just use toggleClass()
   $(".example_wrapper").toggleClass('example_wrapper_active'); 
   $(".example_wrapper_panel").animate({width: "toggle"}, 400);
});

.toggleClass() will add class to target if not exists and remove it again if exists.

Upvotes: 4

Related Questions