Repository navigation
Replies: 1 comment
|
This is an IntersectionObserver limitation, not something specific to inView(). The observer's callback is inherently asynchronous, so it never fires synchronously at setup time, even if the element is already in the viewport the moment the page loads. That's why it only starts reflecting reality once the user scrolls and triggers the first real intersection change. The common fix is to seed the initial state yourself with one manual, synchronous check, then hand off to inView() for everything after that: const el = document.querySelector('#sticky-cta’); // synchronous initial check — runs immediately, no observer delay let visible = isInViewport(el); // inView() takes over for everything after the initial paint If you're doing this inside a React component, run the manual check in useLayoutEffect (fires before paint, so there's no visible flash of the wrong state) rather than useEffect, then let inView()'s enter/leave callbacks keep it updated from there. |
Uh oh!
There was an error while loading. Please reload this page.
Hi there,
I would love to have a utility function to check if an element is in view. For transitioning state I use
inView, but as it's using IntersectionObserver it doesn't run on page load.In my case I'm showing a sticky add to cart button if the default one is not in view. This can differ per screen height, so setting it manually does not solve my issue.
How would you do this?
All reactions