Home > Mobile >  Trigger event when user scroll to position 300 from top?
Trigger event when user scroll to position 300 from top?

Time:11-11

I'm using reactjs and trying to change style of a Div when user scroll from top to position (top 300px). If scrolling down from this position, it will display: block else is none. How do I do this with react? I searched here but all results are not answered mine.

I tried some methods with useRef, handleOnScroll like below function but it doesn't work.

const handleScroll = (e) => {
    const scrolledFromTop = contentRef.current?.scrollTop;
    setActive(scrolledFromTop > 300);
  };
<div ref={contentRef} onScroll={handleScroll}> ... </div>

CodePudding user response:

This might solve your problem:

const handleScroll = (e) => {
  setActive(e.currentTarget.scrollTop > 300);
};

CodePudding user response:

use window.scrollY to watch scroll distance.

const handleScroll = (e) => {
    setActive(window.scrollY > 300);
};
  • Related