intersectionobserver javascript code example
Example 1: IntersectionObserver
var options = {
root: document.querySelector('#scrollArea'),
rootMargin: '0px',
threshold: 1.0
}
var observer = new IntersectionObserver(callback, options);
Example 2: intersection observer example
const images = document.querySelectorAll('.lazyload');
function handleIntersection(entries) {
entries.map((entry) => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
entry.target.classList.add('loaded')
observer.unobserve(entry.target);
}
});
}
const observer = new IntersectionObserver(handleIntersection);
images.forEach(image => observer.observe(image));
Example 3: intersectionobserver
const IntersectionObserverMixin = function (SuperClass) {
return class extends SuperClass {
constructor() {
super();
this.elementVisible = false;
this.IOThresholds = [0.0, 0.25, 0.5, 0.75, 1.0];
this.IORootMargin = "0px";
this.IOVisibleLimit = 0.5;
this.IORemoveOnVisible = true;
this.IODelay = 100;
}
static get properties() {
let props = {};
if (super.properties) {
props = super.properties;
}
return {
...props,
elementVisible: {
type: Boolean,
attribute: "element-visible",
reflect: true,
},
};
}
connectedCallback() {
if (super.connectedCallback) {
super.connectedCallback();
}
if (!this.elementVisible) {
this.intersectionObserver = new IntersectionObserver(
this.handleIntersectionCallback.bind(this),
{
root: document.rootElement,
rootMargin: this.IORootMargin,
threshold: this.IOThresholds,
delay: this.IODelay,
}
);
this.intersectionObserver.observe(this);
}
}
disconnectedCallback() {
if (this.intersectionObserver) {
this.intersectionObserver.disconnect();
}
if (super.disconnectedCallback) {
super.disconnectedCallback();
}
}
handleIntersectionCallback(entries) {
for (let entry of entries) {
let ratio = Number(entry.intersectionRatio).toFixed(2);
if (ratio >= this.IOVisibleLimit) {
this.elementVisible = true;
if (this.IORemoveOnVisible) {
this.intersectionObserver.disconnect();
}
}
}
}
};
};