Skip to content

Commit

Permalink
feat: add smooth scrolling when clicking on hash
Browse files Browse the repository at this point in the history
  • Loading branch information
adrian-ub committed Oct 8, 2024
1 parent 4d51114 commit 1fb6d0f
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 60 deletions.
60 changes: 0 additions & 60 deletions src/components/WrapperPost.astro
Original file line number Diff line number Diff line change
Expand Up @@ -89,63 +89,3 @@ if (config.social?.mastodon) {
</div>
)
}

<script>
function navigate(): true | undefined {
if (location.hash) {
const el = document.querySelector(decodeURIComponent(location.hash))
if (el) {
const rect = el.getBoundingClientRect()
const y = window.scrollY + rect.top - 40
window.scrollTo({
top: y,
behavior: 'smooth',
})
return true
}
}
}

function handleAnchors(event: any): void {
const link = event.target.closest('a')

const isLeftClick = event.button === 0
const isNotPrevented = !event.defaultPrevented
const isNotBlankTarget = link.target !== '_blank'
const isNotExternal = link.rel !== 'external'
const isNotDownload = !link.download
const isNoModifierKey = !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey

// This is so that the linter does not explode. issue: https://github.com/antfu/eslint-config/issues/525
if (link && isNotPrevented && isLeftClick && isNotBlankTarget) {
if (isNotExternal && isNotDownload && isNoModifierKey) {
const url = new URL(link.href)
if (url.origin !== window.location.origin) {
return
}

event.preventDefault()
const { pathname, hash } = url

if (hash && (!pathname || pathname === location.pathname)) {
window.history.replaceState({}, '', hash)
navigate()
return
}

window.location.href = `${pathname}${hash}`
}
}
}

document.addEventListener('DOMContentLoaded', () => {
window.addEventListener('hashchange', navigate)
document.addEventListener('click', handleAnchors, { passive: false })

setTimeout(() => {
if (!navigate()) {
setTimeout(navigate, 1000)
}
}, 1)
})
</script>
1 change: 1 addition & 0 deletions src/styles/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ html {
background-color: var(--c-bg);
overflow-x: hidden;
overflow-y: scroll;
scroll-behavior: smooth;
}

html.dark {
Expand Down

0 comments on commit 1fb6d0f

Please sign in to comment.