1

Lets say I have 2 div tag in my web, the default window's view is the 1st div because it appears at the top.

enter image description here

Refer to the image, the full square is the height of the document that can be scrolled up down. The red box is the portion that can be seen from the device (eg: 1024 x 608). The gray part are the portion that is no longer within the view.

In the example, the tag Div 1 is not within the view anymore because the document already get scrolled to the middle. So, upon the scroll, how do I detect if the Div 1 is no longer visible?

This is what I've done so far :

const [scrollTop, setScrollTop] = useState(0);

useEffect(() => {
    var div_offset = document.getElementById('div1').offsetTop
    if (div_offset.top < window.innerHeight && div_offset.left < window.innerWidth) {
        console.log('still visible')
    } else {
        console.log('not anymore')
    }

    // below is to detect the window scroll
    function onScroll() {
        let currentPosition = window.pageYOffset;
        setScrollTop(currentPosition <= 0 ? 0 : currentPosition);
    }

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

When I do the scrolling, the console is always showing not anymore

Eaten Taik
  • 868
  • 2
  • 12
  • 35

0 Answers0