Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Created December 19, 2012 17:45
Show Gist options
  • Save chrisnicola/4338688 to your computer and use it in GitHub Desktop.
Save chrisnicola/4338688 to your computer and use it in GitHub Desktop.
Pagination using the History API
$(function() {
setPageState = function(current, next) {
$('#content').data('page', current);
history.replaceState({ page: current }, null, current);
if(!next) return;
history.pushState({ page: next }, null, current);
history.go(-1);
};
if (!history) return;
var current = location.href;
var next = $('.pagination a.prev').attr('href');
setPageState(current, next);
onPjaxPopstate = function(e) {
var state = e.originalEvent.state;
if (!state || !state.page) return;
if ($('#content').data('page') === state.page) return;
$(window).unbind('popstate.page-turner');
$.get(state.page, function (data) {
var $content = $(data.match(/<div id="content">([\s\S.]*)<\/div>/i)[0]);
$('#content').html($content).data('page', state.page);
var next = $('.pagination a.prev').attr('href');
setPageState(state.page, next);
$(window).bind('popstate.page-turner', onPjaxPopstate);
});
};
$(window).bind('popstate.page-turner', onPjaxPopstate)
});
@chrisnicola
Copy link
Author

The fourth revision switches to AJAX to load the next content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment