Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react scroll direction

import { useEffect, useState } from "react";

export enum ScrollDirection {
  up = “up”,
  down = “down”,
}

export const useScrollDirection = () => {
  const threshold = 100;
  const [scrollDir, setScrollDir] = useState(ScrollDirection.up);

  useEffect(() => {
    let previousScrollYPosition = window.scrollY;

    const scrolledMoreThanThreshold = (currentScrollYPosition: number) =>
      Math.abs(currentScrollYPosition - previousScrollYPosition) > threshold;

    const isScrollingUp = (currentScrollYPosition: number) =>
      currentScrollYPosition > previousScrollYPosition &&
      !(previousScrollYPosition > 0 && currentScrollYPosition === 0) &&
      !(currentScrollYPosition > 0 && previousScrollYPosition === 0);

    const updateScrollDirection = () => {
      const currentScrollYPosition = window.scrollY;

      if (scrolledMoreThanThreshold(currentScrollYPosition)) {
        const newScrollDirection = isScrollingUp(currentScrollYPosition)
          ? ScrollDirection.down
          : ScrollDirection.up;
        setScrollDir(newScrollDirection);
        previousScrollYPosition =
          currentScrollYPosition > 0 ? currentScrollYPosition : 0;
      }
    };

    const onScroll = () => window.requestAnimationFrame(updateScrollDirection);

    window.addEventListener("scroll", onScroll);

    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return scrollDir;
};
Comment

PREVIOUS NEXT
Code Example
Javascript :: node convert string to hash 
Javascript :: Uncaught TypeError: $(...).jstree is not a function 
Javascript :: get input value angular 
Javascript :: javascript regex stop at first match 
Javascript :: javascript write to firebase 
Javascript :: pass argument to event listener javascript 
Javascript :: what is the function of delete operator in javascript 
Javascript :: location.reload() js 
Javascript :: faker js 
Javascript :: what does getattribute return null for data-* attributes 
Javascript :: usecallback 
Javascript :: js sleep function with argument 
Javascript :: javascript convert number to spreadsheet column 
Javascript :: execute command js 
Javascript :: How to add Select2 on Dynamic element - jQuery 
Javascript :: jquery dropdown selected value show field 
Javascript :: remove specific item from array 
Javascript :: from 0 or 1 to boolean javascript 
Javascript :: express session mongoose 
Javascript :: node mac copy to clipboard 
Javascript :: check if variable is set javascript 
Javascript :: parseint javascript 
Javascript :: how to run a bash script with node js 
Javascript :: javascript connect metamask 
Javascript :: how to run and clone react app 
Javascript :: reverse sort array of objects 
Javascript :: moment format yyyy-mm-dd 
Javascript :: 2d array in js 
Javascript :: react history listen get previous location 
Javascript :: add next to react 
ADD CONTENT
Topic
Content
Source link
Name
4+1 =