Last active
August 29, 2015 14:25
-
-
Save larryprice/b06dd00c3e7f63ae7954 to your computer and use it in GitHub Desktop.
HTML5 History API (https://larry-price.com/blog/2015/07/19/muck-with-history-using-the-html5-history-api/)
This file contains 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
<div id="content" style="margin-bottom: 1.5em;">Welcome</div> | |
<button id="continue" onclick="nextPage()"> | |
Continue | |
</button> | |
<script type="text/javascript" async> | |
function nextPage() { | |
var content = document.getElementById("content"), | |
nextPage = 1; | |
if (content.innerHTML === "Welcome") { | |
updatePageContent(nextPage); | |
} else { | |
nextPage = parseInt(content.innerHTML.slice(5))+1; | |
updatePageContent(nextPage); | |
} | |
history.pushState(nextPage, null, "?page=" + nextPage); | |
} | |
function updatePageContent(pageNumber) { | |
var content = document.getElementById("content"); | |
if (pageNumber === 0) { | |
content.innerHTML = "Welcome"; | |
} else { | |
content.innerHTML = "Page " + pageNumber; | |
} | |
} | |
window.onpopstate = function(event) { | |
updatePageContent(event.state); | |
} | |
window.onload = function() { | |
var currentPage = parseInt(window.location.search.slice(6)) || 0; | |
updatePageContent(currentPage); | |
history.replaceState(currentPage, null, window.location.search); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment