简体   繁体   中英

Adding an event listener with useEffect hook for scrolling

I am using the useEffect hook below to sense the page scroll but it is not logging "yes" to the console. What am I missing? My page is scrolling more than 50px so it should print out "yes".

useEffect(() => {

        const scrollFun = window.addEventListener("scroll", () => {
            if(window.pageYOffset%50 === 0) {
                console.log("yes");
            }
        });

        return () => {
            window.removeEventListener("scroll", scrollFun);
        };        

    }, []);

It's still a bit unclear if you want just a single "page has scrolled 50px" or if you are looking for continual monitoring of scrolling every 50px so I'll try to answer both and you can choose which ever is closer.

Scenario 1 - Scroll first 50px and log

This one is trivial. I suggest using a React ref to "capture" having scrolled the page by at least 50px, resetting when scrolled back.

const scrolled50Ref = useRef();

useEffect(() => {
  const scrollFun = () => {
    if (window.pageYOffset > 50) {
      if (!scrolled50Ref.current) {
        scrolled50Ref.current = true;
        console.log('scrolled 50 px');
      }
    } else {
      scrolled50Ref.current = false;
    }
  }
  
  window.addEventListener("scroll", scrollFun);

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

Scenario 2 - Log every 50px of scrolling

This one isn't as trivial and likely what you are seeing. The issue here is that many browsers use accelerated scrolling, so you won't hit every pageYOffset value. In other words, after scrolling a certain speed/velocity you are likely not to hit an pageYOffset evenly divisible by 50.

The "fix" here is to increase the "window" of divisible by 50.

useEffect(() => {
  const scrollFun = () => {
    if (window.pageYOffset % 50 >= 45) {
      console.log("scrolled 50-ish pixels");
    }
  }
  
  window.addEventListener("scroll", scrollFun);

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

Demo

编辑添加-事件监听器-with-useeffect-hook-for-scrolling(分叉)

Change your if condition with this one:

  if (window.pageYOffset > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM