Why window.innerHeight is bigger than real on mobile?

35 Views Asked by At

I am using Intersection Observer API to handle when specific DOM elements are in the visible area. It works perfectly in the browser but when I switch to mobile (in Chrome DevTools) it has a strange behavior. When I am scrolling the elements remain as intersected long after they leave the visible area.

I noticed that window.innerHeight and document.documentElement.clientHeight differ significantly in that case. For example, if I choose iPhone 12 Pro (390x844px), document.documentElement.clientHeight is 844 as expected but window.innerHeight is 1920.

Where does this difference come from? What I can do to make Intersection Observer API work as expected in mobile too?

This is the related code that I have in my React component:

    const [isIntersecting, setIsIntersecting] = useState(false)
    const ref = useRef<HTMLDivElement>(null)

    useEffect(() => {
        const observer = new IntersectionObserver(([entry]) =>
            setIsIntersecting(entry.isIntersecting),
            {
                rootMargin: "-100px 0px -100px 0px"
            })
        
        observer.observe(ref!.current!);

        return () => observer.disconnect();
    }, [])

    return (
        <div ref={ref}>Content</div>
    )

-100px is desired effect and works as expected on PC.

0

There are 0 best solutions below