Reputation: 15270
What's the proper way to toggle a couple classes on click in jQuery?
1) HTML before click:
<button class="btn"><i class="icon-sign-blank"></i> Click me!</button>
2) HTML after click:
<button class="btn btn-success"><i class="icon-check"></i> Clicked!</button>
3) HTML after another click: (same as beginning)
<button class="btn"><i class="icon-sign-blank"></i> Click me!</button>
Current jQuery:
$('btn').on('click',function(e) {
$('btn > i').removeClass('icon-sign-blank').addClass('icon-check');
$('btn').addClass('btn-success');
});
But this works once, but not back again. What's the proper way to handle both directions?
Upvotes: 1
Views: 214
Reputation: 5304
You can - should - use toggleClass to manage it !
$('btn').on('click',function(e) {
$('btn > i').toggleClass('icon-sign-blank icon-check');
$(this).toggleClass('btn-success');
});
Upvotes: 5
Reputation: 26134
... and without using toggleClass
(if you'd prefer not to use jQuery, this can be done without jQuery as well)
var btnEl = $('btn');
btnEl.on('click', function() {
if (btnEl.hasClass('icon-sign-blank')) btnEl.removeClass('icon-sign-blank');
else btnEl.addClass('icon-sign-blank');
});
Upvotes: 0