samuk samuk - 1 year ago 98
CSS Question

Use on click do not work after ajax call

$(document).ready(function () {
var user = 1;
$("a.like").on("click", function () {
var article = $(this).attr('data-article');
$.ajax({
type: "POST",
url: "WebService.asmx/Like",
data: "{ 'user': '" + user + "', 'article': '" + article + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.d == 1)
{
$(".like[data-article='" + article + "']").fadeOut(700).addClass('unlike').removeClass('like').stop().text('Unlike').fadeIn(700);
}
},
failure: function (msg) {
alert(msg.d);
}
});
});

$("a.unlike").on("click", function () {
var article = $(this).attr('data-article');
$.ajax({
type: "POST",
url: "WebService.asmx/Unlike",
data: "{ 'user': '" + user + "', 'article': '" + article + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.d == 1)
{
$(".unlike[data-article='" + article + "']").fadeOut(700).addClass('like').removeClass('unlike').stop().text('Like').fadeIn(700);
}

},
failure: function (msg) {
alert(msg.d);
}
});
});
});


When I click on a link with class like it's working fine, the same when I click on a link with class unlike. However it doesn't working when I click the same link twice! When I'm searching on the internet, I see that I have to use live instead of click, however live was deprecated on 1.8 version. How can I make this fires multiple times?

Answer Source

Use jQuery.on():

$( document ).on( 'click', 'a.like', function () {
    // Do click stuff here
} );

http://api.jquery.com/on/

You need to bind on to an element that will always be present. (document or some main wrapper div). Using on with the dynamic element will not work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download