Reputation:
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
}
Upvotes: 0
Views: 1395
Reputation: 206008
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.
Upvotes: 2
Reputation: 763
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');
});
Upvotes: 0