-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: update scroll to top with better logic
- Loading branch information
Marvin Heilemann
committed
Mar 4, 2020
1 parent
24b333b
commit a2d506b
Showing
3 changed files
with
39 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import { useLayoutEffect } from 'react' | ||
import debounce from 'lodash/debounce' | ||
|
||
const isBrowser = typeof window !== `undefined` | ||
|
||
function getBoundingRect() { | ||
if (!isBrowser) return { left: 0, top: 0, width: 0, height: 0 } | ||
|
||
return { | ||
left: window.scrollX, | ||
top: window.scrollY, | ||
width: window.innerWidth, | ||
height: window.innerHeight, | ||
} | ||
} | ||
|
||
function handler(event, effect, wait) { | ||
const handleScroll = debounce(() => { | ||
effect(getBoundingRect()) | ||
}, wait) | ||
|
||
window.addEventListener(event, handleScroll) | ||
|
||
return () => window.removeEventListener(event, handleScroll) | ||
} | ||
|
||
function useScroll(effect, wait = 250) { | ||
useLayoutEffect(() => handler('scroll', effect, wait)) | ||
} | ||
|
||
function useResize(effect, wait = 100) { | ||
useLayoutEffect(() => handler('resize', effect, wait)) | ||
} | ||
|
||
export { getBoundingRect, useScroll, useResize } |