i use the following to take a URL e.g. domain.com/#2 and then i use that fragment to redirect the users to domain.com/?page=2.
However, sometimes the user may be shown j
First set a global variable for the page number; then check if the "page" query string variable is set and is numeric (source).
var pageNum = 0;
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if(!isNaN(getParameterByName('page'))) pageNum += parseInt(getParameterByName('page'));
Then check window.location.hash
for the hash. If it is numeric, add it to pageNum
. Else check if it is a command.
if(!isNaN(parseInt(window.location.hash.replace(/#/, '')))) {
pageNum += parseInt(window.location.hash.replace(/#/, ''));
} else if(window.location.hash != null) {
switch(window.location.hash) {
case "feedback":
window.location.href = 'domain.com/feedback';
break;
default:
// do nothing?
break;
}
}
Finally, redirect the user if pageNum > 0
.
if(pageNum > 0) window.location.href = 'domain.com/?page=' + pageNum;
Complete code:
var pageNum = 0;
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if(!isNaN(getParameterByName('page'))) pageNum += parseInt(getParameterByName('page'));
if(!isNaN(parseInt(window.location.hash.replace(/#/, '')))) {
pageNum += parseInt(window.location.hash.replace(/#/, ''));
} else if(window.location.hash != null) {
switch(window.location.hash) {
case "feedback":
window.location.href = 'domain.com/feedback';
break;
default:
// do nothing?
break;
}
}
if(pageNum > 0) window.location.href = 'domain.com/?page=' + pageNum;