Reputation: 8701
I have a page of user comments.
$(p).click(function(){
$(this).hide(200);
});
When user clicks on some comment this one usually disappears. Ok it works perfectly.
But when user does the same with server response, this does not work anymore
Server response is a bunch of next comments found in table (i.e custom AJAX paginator)
Server response looks like this:
<p id="next-id1">bla bla bla 1</p>
<p id="next-id2">bla bla bla 2</p>
Then this response inserts content after particular div which contains first comments in mysql table
like this:
$("#snow-next-btn").click(function(){
$.post('/paginator.php', {}, function(response){
$("#comment-div").after(response);
});
});
Ok it works perfectly as I said. BUT this method:
$(p).click(function){
$(this).hide(200);
}
does not work with server response anymore (but it still works with contents that has been printed by php on page load).
Where is the problem?
Upvotes: 1
Views: 69
Reputation: 60516
You need to use .on()
with selector
parameter (the second argument):
$(document).on('click', 'p', function() {
$(this).hide(200);
})
I can't see your markup, so I can't tell what is the closest parent to p
, but substitute document
to the closest parent of p
, so for example your markup is:
<div id="bla">
<p>...</p>
<p>...</p>
<p>...</p>
</div>
You'd write that as
$('#bla').on('click', 'p', function() {
$(this).hide(200);
})
From docs:
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Upvotes: 1
Reputation: 268344
The event handler has not been bound to the new elements being inserted from the server's response. Instead of using $.click()
, use $.on()
:
$(document).on("click", "p", function(){
$(this).hide( 200 );
});
As new elements come in, they will be bound for you. The only other solution would be to constantly be binding handlers to new elements as they drop in from the server response. Take it easy, sit back, let jQuery do the heavy lifting.
Upvotes: 1