I have a button that does the following:
Sort of like a toggle.
This is the code:
HTML:
<button class="follow_btn btn btn-success" value="1">Follow</button>
CSS:
.btn {
padding:1em;
}
.btn-success {
background:green;
}
.btn-danger {
background:red;
}
jQuery:
$('.follow_btn').on("click", function () {
var this_btn = $(this);
this_btn.removeClass("btn-success follow_btn").addClass("btn-danger unfollow_btn");
});
$('.unfollow_btn').on("click", function () {
var this_btn = $(this);
this_btn.removeClass("btn-danger unfollow_btn").addClass("btn-success follow_btn");
});
and a JSFiddle showing my problem:
http://jsfiddle.net/thedarklord1939/pGuue/
Why is this doing not working? If this is not clear enough, I will elaborate. Thank you.
I have a working jsfiddle here, this is because of a problem binding elements that don't exist when you execute the code that binds events. Tell me if it's clear or not, I can be more detailed.
So this is the key: $(document).on("click", '.unfollow_btn', function () {
It was already said about event delagation, so I will propose one more way to do it even shorter using toggleClass (we need two of them because we need to toggle two pairs at the same time):
$('.follow_btn').on("click", function () {
$(this).toggleClass('unfollow_btn follow_btn').toggleClass('btn-danger btn-success')
});
And the final touch, how to execute different code depending on current button class:
$('.follow_btn').on("click", function () {
if ($(this).hasClass('follow_btn')) {
alert('Follow');
}
else {
alert('Unfollow');
}
$(this).toggleClass('unfollow_btn follow_btn').toggleClass('btn-danger btn-success');
});
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