Run code on component becoming visible for first time
Hey all, I am working on a Tauri application using Solidjs as the frontend framework and am struggling to find a good way to run some code on a component becoming visible for the first time. Ideally, I am trying to make it so this function will run when a list item becomes visible for the first time in order to either download the appropriate image off the internet, or find it on the local disk. I have already created and tested the function to download and check for local images but I am struggling a bit to find a good way to run the function when the component becomes visible. If anyone has any suggestions I would be extremally greatful for any and all help!
8 Replies
you could use
onMount
perhaps in the component
I tried that but unfortantly that runs when the component is mounted to the dom and not necisarily when it becomes visible
Can you define visible?
What would cause the component to not be visible? Are you setting the visiblility via css?
So I have around 60 components which are basically just a list item with a paragraph tag and image. These components are within an unordered list with css making it so there is about 5 list items visible at a time. There is a scrollbar to allow for the items to be scrolled so that all of them can be eventually viewed. Ideally I would like to run the function when the list item first comes into the viewport
You could use a
IntersectionObserver
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
There's also a primitive for it
https://github.com/solidjs-community/solid-primitives/tree/main/packages/intersection-observer#readmeGot it to work by using createViewportObserver() and a boolean signal to check if the element has already been viewed. Thank you for your help!
on an unrelated note, I'd avoid infinite scrolling unless for very specific use cases, pagination is better for ux while also reducing the number of api calls
Hey @Jigz, this is actually for tauri component where I want to only download an image when it is visible for over a certain amount of time. The scroll itself is not infinite but some queries have over 200 results so this helps to only download the images that are actually needed for the user’s experience