You can use hash
(or pushState
method in modern browsers) to "save" the last pagination state. When you load the data, take the page from the hash
.
Here is primitive sample. You can see that if you click on the links to move to another page, then you turn back (using back button or whatever) it's present the previews items.
How it works?
Whenever you click on the links, let's say the first link, which his href
attribute is #1
the event hashchange
was fired. Now, you can read the value of the hash
by using location.hash
(the replace
method uses for remove the #
symbol). Now, if you click on the second link then click back the hashchage
event fired again and so on..
// set data
var data = [],
numOfPages = 5;
for (var i = 0; i < numOfPages; i++) {
data.push([1 + '' + i, 2 + '' + i, 3 + '' + i, 4 + '' + i, 5 + '' + i]);
}
// paging method
var list = document.querySelector('ul');
function getPage(pageNum) {
!pageNum && (pageNum = 0);
var html = '';
for (var i = 0; i < data[pageNum].length; i++) {
html += ('<li>' + data[pageNum][i] + '</li>');
}
list.innerHTML = html;
}
getPage();
// generate pageing buttons
var paging = document.querySelector('#paging'),
pagingHTML = '';
for (var i = 0; i < data.length; i++) {
pagingHTML += ('<a href="#' + i +'">' + i + '</a>');
}
paging.innerHTML = pagingHTML;
// listen to changes in the hash
window.addEventListener('hashchange', function() {
var pageIndex = location.hash.replace('#', '');
getPage(pageIndex);
});
a {
display:inline-block;
margin-left: 10px;
}
<ul></ul>
<div id="paging"></div>