InView-JS

Check when HTML elements are inside the viewport with IntersectionObserver (to keep test off main thread). You can either add classes for various states or provide your own JS callback function.

Usage

To use, simply insert a script with a src pointing to inview.js, then initialise it with “new InView('Selector')” where “Selector” is a valid CSS selector.

<script src="js/inview-1.0.0.ug.js"></script> <script type="text/javascript"> (function(){ new InView('section'); })(); </script>

Optional Parameters

user_options [Object]

Specify your own classes by passing an object as the second parameter. If specified, must be the 2nd parameter. Example:

new InView('Selector', { hidden : 'inview__item--hidden',/* Class to be added when element is outside the viewport */ partial : 'inview__item--partial',/* Class to be added when element is partially in view */ visible : 'inview__item--full',/* Class to be added when element is fully in view */ steps : 10,/* number of steps in the intersectionRatio */ partial_threshold : 0.001,/* The level of visibility at which an element is judged to be partially visible */ visible_threshold : 0.85,/* The level of visibility at which an element is judged to be fully visible */ once: false/* stop observing once full visibility has been achieved? */ });

Events

The following events are available:

inview_initialised - fired on window after the InView script has initialised

inview_hidden - fired on the observed node when the visibility has changed to hidden

inview_partial - fired on the observed node when it becomes partially visible

inview_visible - fired on the observed node when it becomes fully visible

Fixing Cumulative Layout Shift

Turns out this is pretty good at improving the CLS scores on Lighthouse (or whatever dodgy service you're using that's charging you to run Lighthouse on a bargain-bin server).

First things first, I stick an inline style in the <head> (before any other stylesheets are declared)

<style> .cls { opacity: 0 } .cls__seen { opacity: 1; transition: opacity 0.3s linear; } </style>

Then we want to request the JS file in a script somewhere near the bottom of the document, deferred and then triggered on window load:

<script defer src="js/inview-1.0.0.ug.js"></script> <script> function inview_cls_setup(){ new InView('.cls', { hidden : 'cls', partial : 'cls__seen', visible : 'cls__seen', once : true }); } (() => { window.addEventListener('load', inview_cls_setup); })(); </script>

And then just stick the cls class on any HTML element that's giving you Cumulative Layout Shift.

Demo

Red - outside viewport, Green - fully inside viewport, Yellow - partially inside viewport, Magenta - something has gone wrong, check your browser console