Simple Wordpress AJAX pagination
You're using jQuery's load()
method to insert content, which is a shortcut for $.ajax
, which of course inserts the content dynamically.
Dynamic content requires delegation of the events to a non-dynamic parent, something jQuery makes easy with on()
jQuery(function($) { $('#content').on('click', '#pagination a', function(e){ e.preventDefault(); var link = $(this).attr('href'); $('#content').fadeOut(500, function(){ $(this).load(link + ' #content', function() { $(this).fadeIn(500); }); }); });});
I used adeneo's solution, with a couple of minor tweaks.
- My pagination was outside of the container that I wanted to load
, so I performed a separate call for the pagination content. Per the comments, I've updated the code to make a single Ajax call, filtering on the returned data to retrieve and update the desired elements. - My pagination consisted of all links, even for the current page. There was no point in doing an Ajax request if the clicked element is the active page, so I added logic to target only pagination links whose parent list item element did not have the
.disabled
class. - The page jumped every time I loaded new content because it was using fadeOut/In (which sets
display: none;
once the opacity animation is complete). Instead, I manually animate the opacity, which limits the amount of height fluctuation.
Here's the updated code:
$('#content').on('click', '#pagination :not(.disabled) a', function(e){ e.preventDefault(); var link = $(this).attr('href'); $.post( link, function( data ) { var content = $(data).filter('#content'); var pagination = $(data).filter('#pagination'); $('#pagination').html(pagination.html()); $('#content').animate( {opacity: 0}, 500, function(){ $(this).html(content.html()).animate( {opacity: 1}, 500 ); } ); });});