Phillip Rauschkolb Phillip Rauschkolb - 1 year ago 95
Javascript Question

Simple Wordpress AJAX pagination

I'm using the loop + jQuery below to load in the next set of pages, and it works on the first click, but when the next page is loaded in and I click on "newer posts" it reloads the whole page. Any ideas?

<div id="content">
$new_query = new WP_Query();

<?php while ($new_query->have_posts()) : $new_query->the_post(); ?>
<?php the_title(); ?>

<?php endwhile; ?>
<div id="pagination">
<?php next_posts_link('&laquo; Older Entries', $new_query->max_num_pages) ?>
<?php previous_posts_link('Newer Entries &raquo;') ?>
</div><!-- #content -->

$('#pagination a').on('click', function(event){
var link = $(this).attr('href'); //Get the href attribute
$('#content').fadeOut(500, function(){ });//fade out the content area
$('#content').load(link + ' #content', function() { });
$('#content').fadeIn(500, function(){ });//fade in the content area


Answer Source

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){
        var link = $(this).attr('href');
        $('#content').fadeOut(500, function(){
            $(this).load(link + ' #content', function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download