Unlocking the Power of Intersection Observer: Real-World Examples

Unlocking the Power of Intersection Observer: Real-World Examples

Hello! ๐Ÿ‘‹ Welcome back to our exploration of the Intersection Observer API. In our previous section, we delved into the details, discussing both the advantages and limitations of this powerful API. If you missed it, feel free to catch up by reading my last blog post here. Now, letโ€™s take our understanding to the next level as we dive into practical use cases. Buckle up, because weโ€™re about to create some exciting real-world examples! ๐Ÿš€๐Ÿ“.

Ok, enough with the chatter. Let's talk about today's agenda. Like I promised in our last discussion, we will be building a simple landing page to solidify our understanding of this awesome API. ๐ŸŒŸ

The Intersection Observer API is a powerful tool that facilitates visibility tracking of elements within the viewport or their parent elements. Itโ€™s incredibly versatile and has a wide range of practical applications. Here are some real-world scenarios we mentioned earlier where you can leverage this API:

  1. Lazy Loading of Images: Improve page load performance by loading images only when they come into view.

  2. Infinite Scrolling: Dynamically load content as the user scrolls down the page.

  3. Scroll-Spying Navigation Bars: Create navigation menus that highlight active sections based on the userโ€™s scroll position.

  4. Ad View Tracking: Detect whether an ad was viewed by the user.

  5. Article Read Stats: Measure how much of an article a user has read (think medium view vs. read stats).

In the upcoming examples, weโ€™ll focus on the JavaScript involved and demonstrate how to implement some of these use cases using the Intersection Observer API. So, letโ€™s get started! ๐Ÿš€

Before anything, we will be building something like this, with a sticky navigation bar, some text-fade-in animations, and lazy image loading. Let's take a look at some code snippets. Now, for a live experience of how the app works, you can check it out on Code Sandbox or clone my GitHub repo.

Sections:

  1. Setting up the Intersection Observer

  2. Observing Hero for sticky navigation header

  3. Observing section for text-fade-in animations

  4. Observing section for removing blur effects on the image.

    Setting up the intersection observer

The code snippet defines a custom React hook called useInterSectionObserver. This hook utilizes the Intersection Observer API to observe changes in the visibility of a specified DOM element. Letโ€™s break it down:

  1. Hook Signature:

    • The hook takes three arguments:

      • ref: A React ref represents the DOM element to be observed.

      • options: An object that describes how the Intersection Observer should behave (e.g., thresholds, root, rootMargin).

      • callback: A function that will be executed when the observed element intersects with the viewport or its parent element.

  2. Observer Callback:

    • Inside the hook, thereโ€™s a useCallback function that defines the observer callback.

    • This callback creates a new IntersectionObserver instance, passing in the provided callback function and options.

    • The observer is returned from this callback.

  3. Effect Hook:

    • The useEffect hook is used to manage the lifecycle of the observer.

    • When the component mounts or when any of the dependencies (callback, observerCallback, options, or ref) change, the effect runs.

    • If the entity (the observed DOM element) exists, the observer is created using the previously defined callback (observerCallback).

    • The observer starts observing the entity.

    • When the component unmounts or when the entity changes, the cleanup function is executed, which stops observing the entity.

Observing Hero for sticky navigation header

The code defines a custom React component called ObserveHero. This component leverages the Intersection Observer API to observe changes in the visibility of a specified DOM element. Letโ€™s break it down:

  1. Component Signature:

    • The ObserveHero component is a functional component created using the forwardRef function.

    • It accepts two props:

      • children: The child elements to be wrapped by this component.

      • ref: A React ref representing the DOM element to be observed.

  2. Intersection Observer Hook:

    • Inside the component, we use the useInterSectionObserver hook.

    • This hook sets up an intersection observer to observe the provided ref.

    • The observer is configured with a threshold of 0.5, meaning that the callback will be triggered when at least 50% of the observed element is visible in the viewport.

  3. Callback Function:

    • The callback function is executed when the observed element intersects with the viewport.

    • If the element is intersecting, it removes the CSS classes sticky from the .header element.

    • Otherwise, it adds both sticky and shadow classes to the .header.

  4. Child Elements:

    • The ObserveHero component wraps its children with the provided ref.

    • It maps over the children and clones them, ensuring that the ref is passed down to each child.

  5. Summary:

    • This component abstracts away the complexity of manually handling scroll positions and visibility checks.

    • The ObserveHero component is used to create various effects, such as sticky navigation bars or animations triggered by element visibility.

Finally, we make use of our ObserveHero component and observe that when our Hero component is 50% into the viewport, we trigger the sticky behavior of the Header component.

  1. Note: I made use of styled components; if anything seams off, recall its styled components.

Observing section for text-fade-in animations

    1. Component Signature:

      Here too, we forward the children and ref to this component.

    2. Intersection Observer Hook:

      Like before, we make use of our custom useIntersectionObserver hook.

    3. Callback Function:

      • If the element is intersecting, it performs the following actions:

        • Finds the .title element within the observed target and adds the CSS class show-title. This triggers the fade-in animation.

        • Updates the src attribute of an <img> element with the value from its data-src attribute.

        • Sets a timer to add the CSS class title-after to the .title element after a delay of 200 milliseconds.

      • If the element is not intersecting, it clears the timer (if any).

    4. Summary:

      • This section can be used for various effects, such as lazy loading of images, dynamic content transitions, or other interactions triggered by element visibility.

Observing section for removing blur effects on the image.

Ok, I wanted to walk through the section with you, then I thought it's the same as the previously explained section with just a minor change in css styles. So I am going to leave this as a challenge. Try it out and get hands-on experience with how it works. If you face any challenges, don't hesitate to ask. I have made the entire project code available in an interactive section Code Sandbox or visit my GitHub repo.

Conclusion:

Finally, I think this was a long one. What do you think? But what is most important is that we get to see how to take advantage of this awesome API to make amazing transitions between different sections in our demo landing page application. If anything was not clear, don't hesitate to reach out to me.๐Ÿ˜

Remember, challenges are where we learn and grow the most. So, I encourage you to experiment, tweak, and build upon what youโ€™ve learned. If you encounter any hurdles or have questions along the way, feel free to reach out.๐Ÿ˜Š

Keep coding, keep exploring, and happy building! ๐Ÿš€

React to me on Twitter at @CODE_COSTA and GitHub on Aboagye-Dacosta
ย