cookbook home ~ main site ~ other sites ~ podcast ~ twitter ~ mastodon

Use history.pushState() With The Back Button

Overview

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