lazy-observer
is a minimalist script to easily execute function when HTML element is intersecting. Callback can be executed once or every trigger.
More information about the IntersectionObserver
API on MDN.
NPM is the recommended installation method. Install lazy-observer
in your project with the following command:
npm install lazy-observer --save-dev
yarn add lazy-observer --dev
Warning validate-target@3 is ESM.
Note Minimum supported
Node.js
version is16.20.0
.
You can also download it and include it with a script tag. The library will be registered as the global variable window.LazyObserver
.
<script src="https://cdn.jsdelivr.net/npm/lazy-observer@2" crossorigin></script>
Note You can browse the source of the NPM package at jsdelivr.com/package/npm/lazy-observer.
The following example display a console.log
statement when the .footer
HTML element is positioned at one screen height.
new LazyObserver({
elements: document.querySelector('.footer'),
onIntersection: () => console.log('Function is triggered')
});
lazyObserver.observe();
The following example displays a console.log
statement each time the HTML .footer
element is positioned at one screen height.
new LazyObserver({
elements: document.querySelector('.footer'),
once: false,
onIntersection: () => {
console.log('Function is triggered');
}
});
lazyObserver.observe();
The following example displays a console.log
statement when the HTML .footer
element is positioned directly at the bottom of the screen. See the rootMargin
documentation.
new LazyObserver({
elements: document.querySelector('.footer'),
rootMargin: '0px 0px 0px 0px'
onIntersection: () => {
console.log('Function is triggered');
}
});
lazyObserver.observe();
The following example displays a console.log
statement when the HTML .footer
element is positioned directly at the bottom of the screen.
new LazyObserver({
elements: document.querySelector('.footer'),
rootMargin: '0px 0px 0px 0px'
onIntersection: () => {
import(/* webpackChunkName: "footer-video" */ 'footer-video.js'
).then(() => {
console.log('Module footer-video is loaded');
});
}
});
lazyObserver.observe();
Type:
type elements = HTMLElement | HTMLElement[];
Default: null
Tells to the function the target element(s).
Type:
type onIntersection = () => void;
Default: () => {}
Specifies the function to execute when the element is intersecting.
Type:
type once = boolean;
Default: true
Specifies the function is the callback is executed once or at every trigger.
Type:
type rootMargin = string;
Default:
`0px 0px ${window.innerHeight}px 0px`;
Specifies the function the offset for the Intersection Observer.
lazyObserver is licensed under the MIT License.
Created with ♥ by @yoriiis.