Skip to content

Commit 63939f8

Browse files
committed
feat: automatic hash for anchors on scroll
1 parent 33ec49d commit 63939f8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

packages/guide/src/components/SidebarLayout.astro

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,32 @@ type Props = MarkdownLayoutProps<{}>;
1010
const { headings } = Astro.props;
1111
---
1212

13+
<script is:inline>
14+
window.addEventListener('load', () => {
15+
const headings = document.querySelectorAll(
16+
'div.prose > h1, div.prose > h2, div.prose > h3, div.prose > h4, div.prose > h5',
17+
);
18+
19+
const headingsObserver = new IntersectionObserver(
20+
(entries, observer) => {
21+
entries.forEach((entry) => {
22+
if (entry.isIntersecting) {
23+
const location = window.location.toString().split('#')[0];
24+
history.replaceState(null, null, location + '#' + entry.target.id);
25+
}
26+
});
27+
},
28+
{
29+
root: null,
30+
rootMargin: '0px 0px -300px 0px',
31+
threshold: 1.0,
32+
},
33+
);
34+
35+
headings.forEach((heading) => headingsObserver.observe(heading));
36+
});
37+
</script>
38+
1339
<Navbar client:load>
1440
<div class="flex flex-col gap-3 p-3 pb-32 lg:pb-12" slot="pages">
1541
<SidebarItems client:load pages={pages} />

0 commit comments

Comments
 (0)