Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button not binding jQuery class after being inserted

I have a button that does the following:

  1. When pressed, the button removes a class (1) and adds another one (2). This works.
  2. When pressed again, I want to remove the second class (2) and add the first one (1). This does not work.

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.

like image 823
Tiffany Lowe Avatar asked Jul 20 '26 14:07

Tiffany Lowe


2 Answers

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 () {

like image 86
Lorenzo S Avatar answered Jul 22 '26 04:07

Lorenzo S


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')
});

Demo: http://jsfiddle.net/pGuue/3/

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');
});

Demo: http://jsfiddle.net/pGuue/4/

like image 40
dfsq Avatar answered Jul 22 '26 04:07

dfsq