Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Created December 19, 2012 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

This works but has an annoying flicker of the location bar when we push the next page onto the history stack.

@chrisnicola
Copy link
Author

The second revision uses History.js to smooth out some of the quirks in the history API.

@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