Created
April 15, 2020 14:16
-
-
Save TonyDotDev/8e8bf2a8b164d2a3aeae08d7d2ccad1d to your computer and use it in GitHub Desktop.
Get Scroll Position/Direction Webhook
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
import { useState, useEffect } from "react"; | |
export const useScrollPosition = () => { | |
const [scrollPosition, setScrollPosition] = useState(0); | |
const [scrollDirection, setScrollDirection] = useState(-1); | |
useEffect(() => { | |
const scrollYPos = window.pageYOffset || document.documentElement.scrollTop; | |
let lastScrollPos = scrollYPos; | |
const handleScroll = (e) => { | |
const currentScrollPos = e.currentTarget.scrollY; | |
setScrollPosition(currentScrollPos); | |
if (lastScrollPos > currentScrollPos) setScrollDirection(1); | |
else setScrollDirection(-1); | |
lastScrollPos = currentScrollPos; | |
}; | |
window.addEventListener("scroll", handleScroll); | |
return () => { | |
window.removeEventListener("scroll", handleScroll); | |
}; | |
}, []); | |
return { scrollDirection, scrollPosition }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment