Skip to content

Instantly share code, notes, and snippets.

@TonyDotDev
Created April 15, 2020 14:16
Show Gist options
  • Save TonyDotDev/8e8bf2a8b164d2a3aeae08d7d2ccad1d to your computer and use it in GitHub Desktop.
Save TonyDotDev/8e8bf2a8b164d2a3aeae08d7d2ccad1d to your computer and use it in GitHub Desktop.
Get Scroll Position/Direction Webhook
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