surfbird0713
surfbird0713

Reputation: 1219

jQuery toggleClass between two classes after second click

I am trying to toggle between two classes with jQuery

$('.nav-right').toggleClass('open closed');

is toggling both classes at once because neither of those classes are applied in the markup when the page loads, and I don't want them to be. These classes apply an animation that I don't want to show when the page loads.

I'm trying to apply .open on the first click of an element and then apply .closed on the second click, and toggle between the two for every click after.

Here's a simplified pen if you want to check it out the basics in action. Everything I've googled or found on StackOverflow points to toggleClass but that doesn't seem to work in this instance.

Here is another pen with the full animations I'm trying to achieve. You can see how the nav elements fade out one by one from right to left when you click the icon - I want them to fade back in from left to right when you click it again, which I'm achieving by applying the closed class. If I have that class applied to the attribute from the get-go, the nav elements fade in when the page loads which I don't really want.

Upvotes: 0

Views: 1285

Answers (2)

Shanimal
Shanimal

Reputation: 11718

The code will work as is, but you need the initial search-closed* class on the nav-right attribute so the classes toggle into each state.

You can do it with

$('.nav-right').toggleClass('search-closed',true);

Updated Pen

Upvotes: 0

Jainandan singh baghel
Jainandan singh baghel

Reputation: 138

try this,

   $('.nav-right').click(
  function(){
 if($(this).hasClass('open'))
 {
    $(this).removeClass('open');
    $(this).addClass('closed');
  }
 else{
    $(this).addClass('open');
    $(this).removeClass('closed');
     }
  });

Upvotes: 1

Related Questions