forked from
standard.site/standard.site
Standard.site landing page built in Next.js
1const MD_BREAKPOINT = 768
2const MOBILE_OFFSET = 96
3const DESKTOP_OFFSET = 32
4
5export function scrollToElement(href: string, offset?: number) {
6 if (href === '#') {
7 window.scrollTo({ top: 0, behavior: 'smooth' })
8 return
9 }
10
11 const id = href.startsWith('#') ? href.slice(1) : href
12 const element = document.getElementById(id)
13
14 if (element) {
15 const isMobile = window.innerWidth < MD_BREAKPOINT
16 const scrollOffset = offset ?? (isMobile ? MOBILE_OFFSET : DESKTOP_OFFSET)
17 const top = element.getBoundingClientRect().top + window.scrollY - scrollOffset
18 window.scrollTo({ top, behavior: 'smooth' })
19 }
20}