UNPKG

@opuu/inview

Version:

Lightweight JavaScript library for viewport detection with debounced callbacks - intersection observer, lazy loading, scroll animations, infinite scroll, element visibility tracking with TypeScript support. Zero dependencies, ~1KB gzipped.

2 lines (1 loc) 2.18 kB
(function(r,n){typeof exports=="object"&&typeof module!="undefined"?module.exports=n():typeof define=="function"&&define.amd?define(n):(r=typeof globalThis!="undefined"?globalThis:r||self,r.InView=n())})(this,function(){"use strict";class r{constructor(e){this.items=null,this.paused=!1,this.delay=0,this.threshold=[],this.single=!1,this.observers=[],this.debounceTimers=new WeakMap;let s=.01;typeof e=="string"?(this.items=document.querySelectorAll(e),this.delay=0):typeof e=="object"&&(e.delay&&(this.delay=e.delay),e.single&&(this.single=e.single),e.precision==="low"?s=.1:e.precision==="medium"?s=.01:e.precision==="high"&&(s=.001),this.single?this.items=document.querySelector(e.selector):this.items=document.querySelectorAll(e.selector));for(let i=0;i<=1;i+=s)this.threshold.push(i)}debounceCallback(e,s,i){const o=this.debounceTimers.get(e);if(o&&clearTimeout(o),this.delay>0){const t=window.setTimeout(()=>{this.debounceTimers.delete(e),s(i)},this.delay);this.debounceTimers.set(e,t)}else s(i)}pause(){return this.paused=!0,this}resume(){return this.paused=!1,this}setDelay(e){return this.delay=e,this}destroy(){if(this.items instanceof Element){const e=this.debounceTimers.get(this.items);e&&clearTimeout(e)}else this.items instanceof NodeList&&this.items.forEach(e=>{const s=this.debounceTimers.get(e);s&&clearTimeout(s)});return this.debounceTimers=new WeakMap,this.observers.forEach(e=>{e.disconnect()}),this.observers=[],this.paused=!1,this.items=null,this}on(e,s){if("IntersectionObserver"in window){const i=new IntersectionObserver(o=>{o.forEach(t=>{if(e==="enter"&&t.intersectionRatio>0||e==="exit"&&t.intersectionRatio===0){const h={percentage:t.intersectionRatio*100,rootBounds:t.rootBounds,boundingClientRect:t.boundingClientRect,intersectionRect:t.intersectionRect,target:t.target,time:t.time,event:e};this.paused||this.debounceCallback(t.target,s,h)}})},{threshold:this.threshold});this.items instanceof Element?i.observe(this.items):this.items instanceof NodeList?this.items.forEach(o=>{i.observe(o)}):console.error("InView: No items found."),this.observers.push(i)}else console.error("InView: IntersectionObserver not supported.");return this}}return r});