Last active
June 8, 2023 23:41
-
-
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.
This file contains hidden or 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
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