Use history.pushState() With The Back Button
Overview
- This is a work in progress to get the back button working with static pages, history.pushState(), and vanilla JS
- The buttons update the url and change the page contents to match what's in the static file at the same location
- Clicking back and forth works as expected and refreshing the page works as expected
- Clicking the back button doesn't work though, the contents don't change
Working to figure that out
Here's the HTML and JavaScript I have so far
HTML
<div>Current Page: <span id="currentPage">THE_NUMBER</span></div>
<div>
<button id="prevButton">previous</button> ~
<button id="nextButton">next</button>
</div>
JavaScript
let number = THE_NUMBER
const handleNextClick = () => {
setPage(number + 1)
}
const handlePrevClick = () => {
setPage(number - 1)
}
const handlePopState = () => {
console.log('TODO: Figure out if this is gonna work')
}
const init = () => {
document
.getElementById('prevButton')
.addEventListener('click', handlePrevClick)
document
.getElementById('nextButton')
.addEventListener('click', handleNextClick)
}
const setPage = (pageNum) => {
number = pageNum
document.getElementById('currentPage').innerHTML = number
history.pushState({}, '', number + `.html`)
}
document.addEventListener('DOMContentLoaded', init)
window.addEventListener('popstate', handlePopState)
Live Example
Current Page: 0
~
Notes
- The `THE_NUMBER` in the code examples gets turned into an actual number for the examples. I didn't want to have to deal with updating it along with the Live Example display. Hence this placeholder.
- Static files are only generated from -10 to 10. You can go past that with the buttons but it'll break if you try to refresh the pages. I didn't add error handling so the base functionality is easier to see in the example