Created
December 19, 2012 17:45
-
-
Save chrisnicola/4338688 to your computer and use it in GitHub Desktop.
Pagination using the History API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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) | |
}); |
The second revision uses History.js to smooth out some of the quirks in the history API.
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
This works but has an annoying flicker of the location bar when we push the next page onto the history stack.