Skip to content

Commit 3e5cd72

Browse files
committed
fix(Main): Handle scrolling to anchor links
1 parent 41aa614 commit 3e5cd72

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/layouts/Main.astro

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,32 @@ import Navigation from '../components/Navigation.astro'
3838
?.querySelector('html')
3939
?.classList.toggle('pf-v6-theme-dark', themePreference === 'dark')
4040
})
41+
42+
const scrollToHash = (hash: string) => {
43+
const targetElement = document.querySelector(hash)
44+
if (targetElement) {
45+
targetElement.scrollIntoView({ behavior: 'smooth' })
46+
}
47+
}
48+
49+
document.addEventListener('DOMContentLoaded', () => {
50+
if (window.location.hash) {
51+
const hash = window.location.hash
52+
53+
// Without this, page would focus on anchor link without scrolling to it
54+
history.replaceState(null, '', ' ')
55+
56+
setTimeout(() => {
57+
scrollToHash(hash)
58+
history.replaceState(null, '', hash)
59+
}, 500)
60+
}
61+
})
62+
63+
// Handle changes that happen after the initial page load
64+
window.addEventListener('hashchange', () => {
65+
if (window.location.hash) {
66+
scrollToHash(window.location.hash)
67+
}
68+
})
4169
</script>

src/styles/global.scss

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
.ws-heading {
1616
position: relative;
17+
scroll-margin-top: 3rem;
1718
}
1819

1920
.ws-heading-anchor {

0 commit comments

Comments
 (0)