Skip to content

Commit 73fa84f

Browse files
Made scroll to hash more robust
1 parent 3397085 commit 73fa84f

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

packages/cursorless-org-docs/src/docs/components/ScrollToHash.tsx

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,36 @@ export function ScrollToHash() {
1010

1111
useEffect(() => {
1212
if (location.hash) {
13-
setTimeout(() => {
14-
const id = location.hash.replace("#", "");
13+
const id = location.hash.replace("#", "");
14+
const delay = 100;
15+
let attemptsLeft = 5;
16+
17+
const scrollToId = () => {
1518
const element = document.getElementById(id);
19+
1620
if (element != null) {
21+
if (isElementAtTop(element)) {
22+
return;
23+
}
1724
element.scrollIntoView();
1825
}
19-
}, 100);
26+
27+
attemptsLeft--;
28+
29+
if (attemptsLeft > 0) {
30+
setTimeout(scrollToId, delay);
31+
}
32+
};
33+
34+
setTimeout(scrollToId, delay);
2035
}
2136
}, []);
2237

2338
return null;
2439
}
40+
41+
function isElementAtTop(el: HTMLElement, tolerance = 10) {
42+
const rect = el.getBoundingClientRect();
43+
// 68px is the offset for the navbar
44+
return Math.abs(rect.top - 68) <= tolerance;
45+
}

0 commit comments

Comments
 (0)