Reputation: 69
I have a weird problem. I'm currently working on loading posts using PHP, AJAX and MySQL. The code structure itself looks like this:
--- main.js ---
$(window).load(function(){
initAjax();
});
--- ajax.js ---
function initAjax(){
// Toggles a navigation
$(document).on('click', '.btn.open', function(){
... toggles a window ...
});
// Add new posts
$(document).on('click', '.btn.refresh', function(){
$.ajax({
... ajax stuff ...,
success: function(html){
// Show new posts
$('.post_container').prepend(html);
}
});
});
}
When I append new posts they'll show up, but I am not able to click .btn.open anymore - Shouldn't 'on()' fix this? When I go to the Google Chrome console.
Does somebody know a potential way to solve the problem?
FIXED! @cmorrissey found a small solution by replacing $(document) with $('body')
This fix doesn't seem to be a perfect solution since $(document) normally has to work! Since I want clean code, I am totally going to try out @Potherca's Short, Self Contained, Correct, Example method and probably I'll find the solution this way. Thanks
Upvotes: 2
Views: 117
Reputation: 8583
You need to use 'body'
or document.body
instead of document
.
$('body').on('click', '.btn.refresh', function(){
$.ajax({
... ajax stuff ...,
success: function(html){
// Show new posts
$('.post_container').prepend(html);
}
});
});
Reason: The addition of content to the body doesn't bubble up to the document level (http://bugs.jquery.com/ticket/11621), it looks like you can also use window
Upvotes: 1