Search code examples
infinite-scroll

How to add transition to sections on my website


I am making a custom-coded site. I want to add a transition to sections when they come into the viewport. I am not sure if it's called lazy loading or infinite scroll. I am adding an example theme from ThemeForest:

https://wpresidence.net/

You can see that when you scroll down the heading and images become visible with a slight transition. How can I do this on my site?


Solution

  • This could very easily be solved using a scroll event listener on window, tracking exactly when a given HTML section comes into view and then add a class on it that fades it in.

    Or as a much more simpler method, which I'll prefer, you could use the IntersectionObserver API. It allows us to track given elements entering or exiting a reference element, which could be the viewport as well.

    IntersectionObserver can help you determine very easily when a given element enters the viewport. And when that happens, you could add a class on the element to trigger a transition.

    You can learn more about IntersectionObserver at Advanced JavaScript - IntersectionObserver - CodeGuage, and more about the scroll event at JavaScript Scroll Event - CodeGuage.

    As per the CSS to use to power this feature, you'll initially apply visibility: hidden and opacity: 0 to an HTML element, and then once it enters the viewport, add a class that changes these properties to visibility: visible and opacity: 1. Keep in mind that the HTML element must have a transition set in order to get these properties to be changed smoothly.