Skip to content

Instantly share code, notes, and snippets.

@KyleMit
Created April 19, 2019 05:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KyleMit/3bb2e9fa4f97729968e2e07d4df1991e to your computer and use it in GitHub Desktop.
Save KyleMit/3bb2e9fa4f97729968e2e07d4df1991e to your computer and use it in GitHub Desktop.
Page Navigation
var chaperRegex = /(chapter)(\d{1,2})(-)(\d{1,2})/
function LoadNextSection() {
// build next section address
var nextSectionUrl = window.location.href.replace(chaperRegex,
function(match, first, chapter, second, section) {
var nextSection = +section+1 // increment
if (nextSection < 10) nextSection = "0" + nextSection; // pad with 0
return first + chapter + second + nextSection;
});
// make sure page exists by fetching first
$.get(nextSectionUrl,function(data) {
var notFound = data.startsWith("<script")
if (notFound) {
LoadNextChapter();
} else {
ReplacePage(data, nextSectionUrl)
}
})
}
function LoadPrevSection() {
// build next section address
var prevSectionUrl = window.location.href.replace(chaperRegex,
function(match, first, chapter, second, section) {
var nextSection = +section-1 // increment
if (nextSection < 10) nextSection = "0" + nextSection; // pad with 0
return first + chapter + second + nextSection;
});
// make sure page exists by fetching first
$.get(prevSectionUrl, function(data) {
var notFound = data.startsWith("<script")
if (notFound) {
LoadNextChapter();
} else {
ReplacePage(data, prevSectionUrl)
}
})
}
function ReplacePage(data,url) {
// two approaches: either full page re-load, or replace contents and push history
//window.location = url;
var htmlDoc = (new DOMParser()).parseFromString(data, "text/xml");
var $content = $(htmlDoc).find("body .container")
$(".container").html($content.html())
history.pushState({},"next page",url)
}
$("body").on("keyup",function(e) {
if (e.keyCode === 39) {
// go right
LoadNextSection()
} else if (e.keyCode === 37) {
// go left
LoadPrevSection()
}
// else who cares
})
.css("display","block"); // make sure page is visible
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment