Skip to content

Commit 6e34efb

Browse files
committed
Fix cross-route fragment scrolling
1 parent 9d3acf6 commit 6e34efb

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

.changeset/calm-anchors-scroll.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'preact-iso': patch
3+
---
4+
5+
Scroll cross-route URL fragments into view after the destination route commits.

src/router.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,22 @@ function isInScope(href) {
2323
);
2424
}
2525

26+
/** @param {string} url */
27+
function scrollToUrl(url) {
28+
const hash = new URL(url, location.origin).hash;
29+
if (hash) {
30+
try {
31+
const target = document.getElementById(decodeURIComponent(hash.slice(1)));
32+
if (target) {
33+
target.scrollIntoView();
34+
return;
35+
}
36+
} catch {}
37+
}
38+
39+
scrollTo(0, 0);
40+
}
41+
2642
/**
2743
* @param {string} state
2844
* @param {MouseEvent | PopStateEvent | { url: string, replace?: boolean }} action
@@ -274,7 +290,7 @@ export function Router(props) {
274290

275291
// The route is loaded and rendered.
276292
if (prevRoute.current !== path) {
277-
if (wasPush) scrollTo(0, 0);
293+
if (wasPush) scrollToUrl(url);
278294
if (props.onRouteChange) props.onRouteChange(url);
279295

280296
prevRoute.current = path;

0 commit comments

Comments
 (0)