Click to not work after loading ajax content.

How can I make live ('click', function () "work after ajax call and return the content using html (data)? After 4 hours of searching, I think it's better to ask because I'm not going anywhere.

This part works:

$.ajax({ type: "POST", url: "loadAlbum.php", data: dataString, success: function(data){ $(".loader").html(data, {}, function(){ //content is loaded now //need to get the function below working in this part of the content }); }, error : function(data) { } }); }); 

And I need this one to work in ajax above:

 $('.divName as inside loader').live('click',function(){ alert('gotClicked'); var vidItem = $(this).attr('data'); vidItem = vidItem.split('-'); var bookID = vidItem[0]; var state = vidItem[1]; var dataString = 'bookID='+ bookID + '&state=' + state; alert(dataString); }); 
+4
source share
4 answers

.live() deprecated. Use .on() .

 $("body").on("click", "divClass", function(event){ alert('gotClicked'); }); 

Also, to make sure that you call the div correctly, this should not be the name of the div, which should be the class of the div when you call this method.

In addition, the use of live() and on() must be done at the parent level that exists when loading the document. If this divName name that you use did not exist when the page loaded by itself, it cannot be linked. However, if you snap to the body element, then it will always look for a div when clicked.

+20
source
  $(document).delegate(".classname","click",function(){ alert("ok"); }); 
+8
source

Since you are adding HTML data that is returned to you through an ajax call, you need to bind the function after adding the new HTML to the DOM. If you call the code:

 $('.divName as inside loader').live('click',function(){ ... 

before updating the DOM, jQuery will not be able to properly bind the event. I don't know when you parse / customize .live code block code. You must apply the .live code after you have added the returned HTML to the DOM, either in the success callback, or in a function that is called immediately after the callback (if any).

Hope this helps.

0
source

Simple as the data is added after js loading, you will need to ...

 $(selector).live('click', function(e){ alert('this is a click'); }); 

Be warned that if you do this very often, this may be useful, but in some cases it is better to manually unlock and reconfigure.

0
source

All Articles