Sonya Panich Sonya Panich - 1 year ago 104
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 ');
else if (this.class= 'btn-success'){
$('#critical_btn').removeClass('btn-success').addClass('btn-default ');

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. (

jQuery would look like this:

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