Skip to content

React how to select how much I have scrolled below

I am trying to select some value preferably px of how much I have scrolled down so I can conditionally hide the element.

Something like total height - scrolled height would be ideal

Problem

I’m having trouble selecting the proper property.

console.log doesn’t help as it renders the actual body tag then.

Here’s the code

const scrollHandler = (event) => {
    let scrollTop = event.srcElement.body.offsetHeight;
    console.log(scrollTop)
    setIsSearchVisible(false)
}

useEffect(() => {
    window.addEventListener('scroll', scrollHandler, true);
    return () => {
      window.removeEventListener('scroll', scrollHandler, true);
    }
},[])

Would also appreciate it if someone could point me to the documentation of the same thanks!

Answer

I was able to figure it out , Instead of using the event object I simply used the window object, Something like this

const scrollHandler = (event) => {
    let scrollTop = window.scrollY;
    console.log(scrollTop);
    setIsSearchVisible(false);
  };

  useEffect(() => {
    window.addEventListener("scroll", scrollHandler, true);
    return () => {
      window.removeEventListener("scroll", scrollHandler, true);
    };
  }, []);