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!
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/
You can use hasClass
Method :
$(document).ready(function() {
$("#critical_btn").click(function () {
if ($(this).hasClass('btn-default')){
$('#critical_btn').removeClass('btn-default').addClass('btn-success');
$(this).addClass('btn-success').removeClass('btn-default');
}
else if ($(this).hasClass('btn-success')){
$('#critical_btn').removeClass('btn-success').addClass('btn-default');
$(this).addClass('btn-default').removeClass('btn-success');
}
})
})
Final code :
<!DOCTYPE html>
<html>
<head>
<style>
.btn-success {background-color: red}
.btn-default {background-color: blue}
</style>
</head>
<body>
<button id="critical_btn" class="btn-default">Button</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#critical_btn").click(function () {
if ($(this).hasClass('btn-default')){
$('#critical_btn').removeClass('btn-default').addClass('btn-success');
$(this).addClass('btn-success').removeClass('btn-default');
}
else if ($(this).hasClass('btn-success')){
$('#critical_btn').removeClass('btn-success').addClass('btn-default');
$(this).addClass('btn-default').removeClass('btn-success');
}
})
})
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With