Reputation: 1214
How can I make live('click',function()" work after an ajax call and returning content with html(data)? After 4 hrs of searching I think I'd better ask because I am getting nowhere.
This part is working:
$.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 the 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);
});
Upvotes: 8
Views: 30925
Reputation: 101
$(document).delegate(".classname","click",function(){
alert("ok");
});
Upvotes: 10
Reputation: 112
Simple, as the data is appended after the js is loaded you will need to go with...
$(selector).live('click', function(e){
alert('this is a click');
});
Be warned that there is a performance hit if you do this a lot, it may be better to manually unbind and rebind in some cases.
Upvotes: 0
Reputation: 12508
Since you are appending HTML data that is returned to you via an ajax call, you need to bind the function after the new HTML has been added to the DOM. If you call the code:
$('.divName as inside loader').live('click',function(){ ...
before the DOM has been updated, jQuery will not be able to bind the event properly. I don't know when you are parsing/setting up the code .live code block. You've got to apply the .live code after you have appended the returned HTML to the DOM, either in the success callback or the function that is called right after the success callback (if there is one).
Hope this helps.
Upvotes: 0
Reputation: 37533
.live()
is deprecated. Use .on()
instead.
$("body").on("click", "divClass", function(event){
alert('gotClicked');
});
Also, just to make sure you're calling the div correctly, it shouldn't be the div name it should be the div class when calling it in that fashion.
Also, using live()
and on()
needs to be applied at a parent level that exists at the document load. If this divName you're using didn't exist when the page loaded itself it can't be bound to. However, if you bind to the body element, then it'll always look for the div when the click occurs.
Upvotes: 25