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.
Because you’re delegating the event to the
documentobject, the handler is bound ondocument, not on each individual.likecommentelement.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
likecommentclass as it would probably be associated with styles.Instead, use a selector that forces a non-match when another class is added.
doneis being used for this example, although it could befinished,liked, or some other class name you prefer:And when you want to stop the element from causing a click event, add the
doneclass to the element:Adding the new class also provides a hook for changing the styles of
likecommentso that it no longer looks clickable.