Sonya Panich Sonya Panich - 1 year ago 120
CSS Question

How to toggle between bootstrap button classes onClick?

I am using Bootstrap buttons and would like them to change color when clicked. For example, the button is originally gray (btn-default) and should change to green (btn-success) on click. I would like the button to change back to the default class when clicked again. So far I have created an if statement and added the following code, however it is only changing color once, and will not return to the default class when clicked again.

$("#critical_btn").click(function () {

if (this.class= 'btn-default'){
$('#critical_btn').removeClass('btn-default').addClass('btn-success ');
$(this).addClass('btn-success').removeClass('btn-default');
}
else if (this.class= 'btn-success'){
$('#critical_btn').removeClass('btn-success').addClass('btn-default ');
$(this).addClass('btn-default').removeClass('btn-success');
}
});


I am fairly new to this, so any help would be greatly appreciated!

Answer Source

Instead of doing and if elseif statement. If you want to toggle between two classes you can use $(selector).toggleClass('firstclass secondclass') as long as one on them will be assigned in the markup. (http://api.jquery.com/toggleclass/)

jQuery would look like this:

$("#critical_btn").click(function() {
  $(this).toggleClass('btn-default btn-success');
});

Example:

https://jsfiddle.net/xsotp27s/