0

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.

2 Answers 2

1

try this,

   $('.nav-right').click(
  function(){
 if($(this).hasClass('open'))
 {
    $(this).removeClass('open');
    $(this).addClass('closed');
  }
 else{
    $(this).addClass('open');
    $(this).removeClass('closed');
     }
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this approach did it for me!
0

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

2 Comments

Thanks, but that's not quite what I want. I don't want to have to apply closed to the attribute initially. I updated my question with a second pen so you can see what I'm trying to achieve. I appreciate your help!
That seems to still be adding one of the classes initially when the page loads. All the nav elements should appear at the same time, with the rest of the page at first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.