jQuery Script for Loading More Posts

AKA Twitter, Facebook and Tumblr style.

jQuery(document).ready(function($) {

	var $content = '#content';
	var $nav_wrap = '.navigation';
	var $anchor = '.navigation .alignleft a';
	var $text = 'Load More';

	var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts

	$($nav_wrap).html('<a id="almc-load-more" href="' + $next_href + '">' + $text + '</a>');

	$('#almc-load-more').click(function(e) {
		e.preventDefault();

		$.get($(this).attr('href'), '', function(data) {
			var $timestamp = new Date().getTime();
			var $new_content = $($content, data).wrapInner('<div class="almc-loaded" id="almc-' + $timestamp + '" />').html(); // Grab just the content
			$next_href = $($anchor, data).attr('href'); // Get the new href

			$('html,body').animate({scrollTop: $($nav_wrap).position().top}, 'slow'); // Animate scroll

			$($nav_wrap).before($new_content); // Append the new content
			$('#almc-' + $timestamp).hide().fadeIn('slow'); // Animate load
			$('#almc-load-more').attr('href', $next_href);	// Change the next URL
			$('.almc-loaded ' + $nav_wrap).remove(); // Remove the original navigation
		});
	});

});

Leave a Reply