JavaScript: implementing the scrolling into view effect with IntersectionObserver

JavaScript: implementing the scrolling into view effect with IntersectionObserver

Modern JavaScript allows us to handle the effect of scrolling into view in a native way.

Modern JavaScript allows us to handle the effect of scrolling into view in a native way.

IntersectionObserver implements the observer pattern for the DOM elements that actually are reached by the scrolling action. So when an element intersects the viewport area, its isIntersecting property is set to true.

This class must be instantiated by passing a callback function whose first argument are/is the DOM element(s) to observe. It also accepts a configuration object where we can specify the root element from which we can start monitoring the intersections. A value of null for the root property equals to monitoring the whole document.

Once we pass elements to the class with the observe() method, they are accessible as normal DOM elements only through the target property of each entry object. In this case we need this property to add the CSS class that triggers the transition.


'use strict';

const scrollIntoView = () => {
    const root = document.querySelector('#content');
    const posts = root.querySelectorAll('article');

    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
           if(entry.isIntersecting) {
               const visiblePost = entry.target;
               visiblePost.classList.add('in');
           }
        });
    }, {
        root: null
    });

    Array.prototype.forEach.call(posts, post => {
       observer.observe(post);
    });
};

document.addEventListener('DOMContentLoaded', () => {
   scrollIntoView();
});

You can see the above code in action on the following page.