Skip to content

Instantly share code, notes, and snippets.

@jon49
Last active June 8, 2023 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jon49/13e2c9dfd638b78077519179e8dc210d to your computer and use it in GitHub Desktop.
Save jon49/13e2c9dfd638b78077519179e8dc210d to your computer and use it in GitHub Desktop.
MPA progressive enhancement for scrolling back to position and focusing on previously focused element.
function getCleanUrlPath() {
let url = new URL(document.location.href)
return url.pathname.replace(/\/$/, "")
}
window.addEventListener('beforeunload', () => {
let active = document.activeElement
localStorage.pageLocation = JSON.stringify({
href: getCleanUrlPath(),
y: window.scrollY,
height: document.body.scrollHeight,
active: {
id: active?.id,
name: active?.getAttribute('name')
}
})
})
function onLoad() {
if (document.querySelector('[autofocus]')) return
let location = localStorage.pageLocation
if (!location) return
let { y, height, href, active: { id, name } } = JSON.parse(location)
if (y && href === getCleanUrlPath()) {
window.scrollTo({ top: y + document.body.scrollHeight - height })
}
let active =
document.getElementById(id) ||
document.querySelector(`[name="${name}"]`)
if (active) {
active.focus()
// @ts-ignore
active.select instanceof Function && active.select()
}
}
onLoad()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment