Overview
This module consists solely of the JavaScript file located at dist/script/inview.js. There is no corresponding stylesheet.
The idea behind this module comes from the jQuery inview module, first created by Remy Sharp and then later rewritten by Christopher Blum. Those implementations calculate the viewport and element sizes and create a custom event handler to check for the appearance of an element in the browser's viewport.
This implementation uses the Intersection Observer API. The code is adapted from the examples provided with the API documentation and on Google's image lazy loading script.
Details
This module allows you to apply styles or actions to an element when the element first moves into the browser’s viewport. The styles or actions are triggered by a state class that is added to the element when it moves into view.
An element is considered in view when 25% of the element’s (rectangular) bounding box is in the viewport.
An element can only move into view once. No subsequent state changes will occur even if the element moves out of and then back into the viewport again.
Classes
- .make-inview
- Apply this class to any element to indicate that the element should be observed by the Intersection Observer API.
- .not-inview
- This class is applied as the default state to any element that has the .make-inview class. You can use this class to apply default state styles. This class is removed when the element comes into view.
- .inview
- When an observed element comes into view, the .not-inview class is removed and this class is applied. You can use this class to apply end-state styles or as a trigger for further action.
Example
A simple CSS transition occurs for each heading and paragraph in this page when the element comes into view. You can inspect the code to see the change of state class as you scroll down the page.