Intersection Observer

In my homepage I created an animation whenever a user scroll to a certain section in the homepage. For example when we scroll to the about section, the content appears with a fade in animation. 

At start I wrote code using the scroll event:


window.addEventListener('scroll', event => {

 console.log(window.scrollY)

 console.log(window.scrollX) 

})

For every scroll we can get the window Y coordinate and check it with the Y coordinate of the element we scrolling to using the Element.getBoundingClientRect. But using scroll event listener is not efficient because It fires a lot of times during scrolling, not just at the end or beginning of the scrolling.

With the Intersection Observer we can achieve this effect more efficiency. It can detect when an element on the page is actually visible to the user. It doesn’t fires multiple events in each scroll and we don’t have to get the Y coordinate of the scrolled element with the Element.getBoundingClientRect.

There are many use cases for this kind of behavior, not only to animate stuff when element is visible. we can also use this kind of detection to delay the loading of images until they’re visible, or to start and stop a video, or to see if an ad has actually been viewed by the user and without degrade the browser’s performance. 

Let’s implement a basic example of the Intersection Observer. We will have a page with text and at the end of the page we will have a div called target-element. when the target-element is not visible, the background color of the div will be red. When the target-element is partially visible, its background will be yellow and when its fully visible it will be green.  Check the example in codepen: https://codepen.io/nisan-sabag/pen/pooNNRL.

This is the code:


<!doctype html>
<html>
    <head>
        <title>IntersectionObserver API
    

    <body>
        <h1>IntersectionObserver API
        <div>
            <p class="lorem">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
            

<p class="lorem"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

<p class="lorem"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

<p class="lorem"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

<!-- This is the element we want to watch for visibility --> <div id="targetElem">Target Element </div> <p class="lorem">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

</div> <script> window.addEventListener("load", function () { // Create a new Observer var observer = new IntersectionObserver(function (entries) { // log the callback data to the console output console.log(entries); if (entries[0].intersectionRatio < 0.5) { entries[0].target.className = "red" } if (entries[0].intersectionRatio >= 0.5 && entries[0].intersectionRatio < 1) { entries[0].target.className = "yellow" } if (entries[0].intersectionRatio >= 1) { entries[0].target.className = "green" } }, { "threshold": [0, 0.5, 1] }); // Start observing the target element observer.observe(document.getElementById("targetElem")) }) </script> </body> </html>