I know this has been asked on SO a lot, but I have trawled through the posts for a few hours now and nothing works.
I’m working on a WordPress blog where the prev/next buttons on a single post page have to load the prev/next post by Ajax. I have written the code (jQuery Ajax) all fine (I think – if you want to improve it, be my guest!), but in each post there a few bits of jQuery that need to work. However, after I click either of the prev/next buttons to move between posts, the jQuery won’t work (it works absolutely perfectly when the page is first loaded). I know this is due to the content not being ‘connected’ to the JS anymore but I’m not sure what to do about it.
Here is my code:
$(".page-feed").on('click', '.post-nav>a', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var link = $(this).attr('href'); // get the value of the href attribute on the links
$(".post-content").html("Loading...");
$.get(link, function(result) {
$result = $(result);
$content = $result.find(".post-content");
$(".post-content").replaceWith($content);
}, 'html');
});
I know that you’re probably going to ask what I’ve already tried, but if I’m honest, not a lot that would be worth putting here.
The code above is located right at the top of a file called script.js, with all the other JS below it (which doesn’t currently work after the Ajax call). The script is started by the standard $(document).ready(function() {
statement.
Thanks for any help 🙂
First, you need to accept the event object as an argument.
Next, by using the jQuery event object, you can simplify the next line because
event
is normalized by jQuery to work cross-browser.Now, as far as it working on the first click but not after, that’s likely because
.page-feed
is a dynamic element. You’ll need to instead select an element that is an ancestor of.post-content
.document
is a decent replacement, but it would be better if you picked one more local.