user1683645
user1683645

Reputation: 1579

unbind click inside on();

I'm having problem unbinding a click event on a specific element. this is my JS code.

    $(document).on('click','.likecomment', function(e){
        e.preventDefault();
        var commentid = $(this).data('commentid');
        $.ajax({
            type: 'POST',
            url: '?category=likecomment',
            data: {
                "commentid" : commentid
            },
            success: function(){
                $(this).unbind('click');
                var likes = $('#'+commentid+'-likes').text();
                likes++;
                $('#'+commentid+'-likes').html(likes);
            }
        });
    return false;
});

The functionality of an element persist after one click. How can I prevent it from being clickable after first click? If the code is correct I'll probably figure out the problem myself but I just want to make sure that the code is correct or not.

Upvotes: 0

Views: 584

Answers (3)

user659025
user659025

Reputation:

This might be because you're unbinding within the success handler. If your ajax call takes a while then your unbind will also take a while. So after your $.ajax try:

$(this).prop({disabled: true});

Upvotes: 1

Kevin B
Kevin B

Reputation: 95022

Use the matching .off syntax.

$(document).off('click','.likecomment');

or make the current element no longer match .likecomment

$(this).removeClass("likecomment");

or

$(this).removeClass("delegated");
// with this change to binding method:
$(document).on('click','.likecomment.delegated', function(e){

However keep in mind that this inside of your success call is not the same this outside of it, you need to add this ajax option: context: this, so that the this inside your ajax will be the same as it is outside your ajax.

Upvotes: 3

zzzzBov
zzzzBov

Reputation: 179066

Because you're delegating the event to the document object, the handler is bound on document, not on each individual .likecomment element.

You wouldn't want to unbind the event in case there are multiple elements that the delegated event would match, and you probably wouldn't want to remove the likecomment class as it would probably be associated with styles.

Instead, use a selector that forces a non-match when another class is added. done is being used for this example, although it could be finished, liked, or some other class name you prefer:

$(document).on('click', '.likecomment:not(.done)', function () {...});

And when you want to stop the element from causing a click event, add the done class to the element:

$(this).addClass('done');

Adding the new class also provides a hook for changing the styles of likecomment so that it no longer looks clickable.

Upvotes: 1

Related Questions