0

I have a default class. When the icon has been clicked, the default class will be removed and replaced with the new one, then when the icon has been clicked again, then the old class will be added again, then the new class will be removed. It should be changed every time the icon is clicked. It's closed to .toggleClass(), but should show/hide and replace the class.

Here is my js code

var MenuIcon = $('.menu-icon-plus'),
    MenuSidebar = $('.sidebar');

  MenuIcon.click(function(){
    if ($(MenuSidebar).hasClass('test')) { //existing class
      $(MenuSidebar).removeClass('test');
    } else {
      $(MenuSidebar).addClass('test2'); // replacement of old class
    }
1
  • 1
    That's a good reason to start doing things simple and not use a default class but style the defaults as-is. Than toggle the special class only. Commented Jul 3, 2015 at 0:41

2 Answers 2

2

Add the two classes to toggleClass("default special") to swap them:

$("button").on("click", function(){

  $(this).toggleClass("default special");
  
});
.default{
  background:lime;
  font-size:2em;
}
.special{
  background:gold;
  /* I don't have font size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="default">TEST</button>

P.S: If you wanted to only change the background, than toggleClass("special") would suffice.
Or, again using only .toggleClass("special") you could set directly in CSS the reset styles, but that just complicates stuff. It clearly depends on the use case.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. The code works. I just did not know that the .toggleClass can be swapped into two different class.
@AyiieMiguel yes, that cool functionality is a bit obfustaced inside the toggleClass Docs, but it's there.
0

Try this. Replace the classes as per your requirement.

$(document).on('click', '.oldclass', function() {   

            $(this).removeClass('oldclass').addClass('newclass'); 
    });

    $(document).on('click', '.newclass', function() { 

            $(this).removeClass('newclass').addClass('oldclass');
    });

Comments

Your Answer

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