user4175297 user4175297 - 1 month ago 10
Ajax Question

Detect a click on a div that's inside an Ajax call

I'm trying to detect a click on a div by its class name that comes from a Ajax call using the .click handler. It works, but it seems when ajax fetches records a few times, my click handler breaks and keeps duplicated itself. Thus my function gets triggered multiple times when clicked once.

JQUERY

$.ajax({ ...
success: function(data){

//add to favorite function - THIS CLICK HANDLER KEEPS DUPLICATING
$('.favit').click(function(){
var cid=$(this).data("id");
addfav(cid); //execute function
return false;
});

},...


And if I try and pull this function out of the ajax call the click isn't detected.

Answer

You need to use .on() and delegate the events.

 $.ajax({ ...
   success: function(data){

    //add to favorite function - THIS CLICK HANDLER KEEPS DUPLICATING 

  },

$(document).on("click", '.favit', function(){
  var cid=$(this).data("id");
  addfav(cid); //execute function
  return false;
});