Files
web/hooks/useScrollToTop.ts
Erik Tiekstra e3b1bfc414 Merged in feat/SW-1454-hotel-listing-city-page (pull request #1250)
feat(SW-1454): added hotel listing

* feat(SW-1454): added hotel listing


Approved-by: Fredrik Thorsson
2025-02-05 13:10:28 +00:00

47 lines
1.3 KiB
TypeScript

import { type RefObject, useEffect, useState } from "react"
interface UseScrollToTopProps {
threshold: number
elementRef?: RefObject<HTMLElement>
refScrollable?: boolean
}
export function useScrollToTop({
threshold,
elementRef,
refScrollable,
}: UseScrollToTopProps) {
const [showBackToTop, setShowBackToTop] = useState(false)
useEffect(() => {
const element =
refScrollable && elementRef?.current ? elementRef?.current : window
function handleScroll() {
let position = window.scrollY
if (elementRef?.current) {
position = refScrollable
? elementRef.current.scrollTop
: elementRef.current.getBoundingClientRect().top * -1
}
setShowBackToTop(position > threshold)
}
element.addEventListener("scroll", handleScroll, { passive: true })
return () => element.removeEventListener("scroll", handleScroll)
}, [threshold, elementRef, refScrollable])
function scrollToTop() {
if (elementRef?.current) {
if (refScrollable) {
elementRef.current.scrollTo({ top: 0, behavior: "smooth" })
}
window.scrollTo({ top: elementRef.current.offsetTop, behavior: "smooth" })
} else {
window.scrollTo({ top: 0, behavior: "smooth" })
}
}
return { showBackToTop, scrollToTop }
}