0

I was wondering how to do something more efficiently in jQuery and that is switch a class to another class on click on #trigger.

So on odd clicks, class a ( .a ) will be given to all <nav>s in the document and then on even clicks, class a ( .a ) will be remove / switched-out and replaced with class b ( .b ).

The only way i could think about doing this is by adding the new class and removing the current class, but i'm sure there has to be a more efficient way of doing this.

4
  • 1
    stackoverflow.com/questions/244392/jquery-toggle-state Commented Mar 8, 2013 at 19:50
  • 4
    You might find the aptly-named .toggleClass() helpful. Commented Mar 8, 2013 at 19:52
  • @DanielA.White Just what I described above. Adding and removing classes with .addClass() and .removeClass() Commented Mar 9, 2013 at 2:48
  • @Juhana Ah, thank you. it is aptly-named. Commented Mar 9, 2013 at 2:49

1 Answer 1

4
 $('.a').on('click',function(){
      $(this).toggleClass('a b');
 });
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for this. Why use .on('click'... instead of .click() ?
.click is just shorthand for .on('click' but the on method is more powerful. So I always just use .on

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.